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.
思路:利用堆栈。
当'(' '[' '{' 出现时让他们入堆栈,当')' ']' '}'出现时,取栈顶元素看是否与其匹配,若匹配出栈,不匹配返回false。
最后如果栈元素为零,则括号匹配。
特别注意当栈元素为零时,不要再执行出栈操作,直接返回false。
class Solution {
public:
bool isValid(string s) {
if(s.size()==0)
return false;
stack<char> stk;
for(int i=0;i<s.size();++i){
if(s[i]=='{'||s[i]=='['||s[i]=='(')
stk.push(s[i]);
if(s[i]=='}'||s[i]==']'||s[i]==')'){
if(stk.size()==0)
return false;
if((s[i]==')'&&stk.top()!='(')||(s[i]=='}'&&stk.top()!='{')||(s[i]==']'&&stk.top()!='['))
return false;
stk.pop();
}
}
if(stk.size()==0)
return true;
}
};