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.length()%2 != 0)
return false;
if(s.length() == 0)
return true;
stack<char> stk;
for(int i=0;i<s.length();i++){
if(s[i] == ')' || s[i] == ']' || s[i] == '}'){
if(stk.empty()){
return false;
}
if(isDoubleStr(stk.top(),s[i])){
stk.pop();
}else{
return false;
}
}else{
stk.push(s[i]);
}
}
if(stk.empty())
return true;
else
return false;
}
bool isDoubleStr(char a,char b){
switch(a){
case '(':
if(b == ')')
return true;
else
return false;
case '[':
if(b == ']')
return true;
else
return false;
case '{':
if(b == '}')
return true;
else
return false;
default:
return false;
}
}
};