题目:
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) {
if(s.empty()) return true;
if(s.size()%2) return false;
stack<char> sta;
for(int i = 0; i < s.size(); ++i){
switch(s[i]){
case '(':
case '{':
case '[': sta.push(s[i]);break;
case ')':
if(sta.empty()) return false;
if('(' != sta.top()) return false;
sta.pop();
break;
case '}':
if(sta.empty()) return false;
if('{' != sta.top()) return false;
sta.pop();
break;
case ']':
if(sta.empty()) return false;
if('[' != sta.top()) return false;
sta.pop();
break;
default:return false;//若为其他字符,直接返回false
}
}
return sta.empty();//可能存在多余的左括号,所以要检查栈是否为空
}
};