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.
class Solution {
public:
bool isValid(string s) {
int len = s.size();
if(len == 0) return true;
stack<char> st;
for(int i = 0; i < len; i++) {
//入栈
if(s[i] == '(' || s[i] == '{' || s[i] == '[') {
st.push(s[i]);
} else {
//出栈
if(st.empty()) return false;
char left = st.top();
st.pop();
if(left == '(' && s[i] != ')') {
return false;
} else if(left == '{' && s[i] != '}') {
return false;
} else if(left == '[' && s[i] != ']') {
return false;
}
}
}
if(!st.empty()) return false;
return true;
}
};