Given a string containing just the characters '(', ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
Have you met this question in a real interview?
Example
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
LeetCode上的原题,请参见我之前的博客Valid Parentheses。
class Solution {
public:
/**
* @param s A string
* @return whether the string is a valid parentheses
*/
bool isValidParentheses(string& s) {
stack<char> st;
for (char c : s) {
if (c == ')' || c == '}' || c == ']') {
if (st.empty()) return false;
if (c == ')' && st.top() != '(') return false;
if (c == '}' && st.top() != '{') return false;
if (c == ']' && st.top() != '[') return false;
st.pop();
} else {
st.push(c);
}
}
return st.empty();
}
};