題目:
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
鏈接:Valid Parentheses
解法:遍歷字符串,左括號入棧,右括號檢查棧頂元素,若不對應立即返回失敗。時間O(n)
class Solution {
public:
bool isValid(string s) {
stack<char> st;
int len = s.length();
for (int i = 0; i < len; i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
st.push(s[i]);
} else if (!st.empty() && s[i] == ')') {
if (st.top() == '(') st.pop();
else return false;
} else if (!st.empty() && s[i] == ']') {
if (st.top() == '[') st.pop();
else return false;
} else if (!st.empty() && s[i] == '}') {
if (st.top() == '{') st.pop();
else return false;
} else {
return false;
}
}
return st.empty();
}
};
Runtime: 3 ms