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.
Subscribe to see which companies asked this question
设置一个栈,保存左边的括号,与右边的括号匹配对应。
class Solution {
public:
bool isValid(string s) {
int len=s.size();
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;
else {
int t=st.top();
if ((t == '(' && s[i] != ')') || (t == '[' && s[i] != ']') || (t == '{' && s[i] != '}'))
return false;
st.pop();
}
}
}
return st.empty();
}
};