Valid Parentheses
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 "([)]"
class Solution {
public:
//栈实现
bool isValid(string s) {
int i;
char pre;
stack<char> ss;
for(i=0;i<s.length();i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{')
ss.push(s[i]);
else{//右边
if(ss.empty())
return false;
pre=ss.top();//栈里面弹出左边的看是否匹配
switch(s[i]){
case ')':
if(pre=='(')
ss.pop();
else
return false;
break;
case ']':
if(pre=='[')
ss.pop();
else
return false;
break;
case '}':
if(pre=='{')
ss.pop();
else
return false;
break;
}
}
}
if(ss.empty())
return true;
else
return false;
}
};