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.
class Solution {
public:
bool isValid(string s) {
stack<char> schar;
//char table[] = "(){}[]";
for(int i = 0; i < s.size(); ++i){
if(schar.empty() ){
schar.push(s[i]);
}else{
switch (schar.top()){
case '(':
if(')' == s[i]) schar.pop();
else schar.push(s[i]);
break;
case '{':
if('}' == s[i]) schar.pop();
else schar.push(s[i]);
break;
case '[':
if(']' == s[i]) schar.pop();
else schar.push(s[i]);
break;
default: return false;
}
}
}
return schar.empty();
}
};