题目:
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.
思路:
1.简单的栈处理
代码:
class Solution{
public:
bool isValid(string s)
{
if(s.size()%2)
return false;
stack<char> stk;
char tmp;
for(int i=0;i!=s.size();++i)
{
if(s[i]=='(' || s[i]=='[' || s[i]=='{')
stk.push(s[i]);
else
{
if(!stk.size())
return false;
tmp=stk.top();
if((s[i]==')' && tmp!='(') || (s[i]==']' && tmp!='[') || (s[i]=='}' && tmp!='{'))
return false;
stk.pop();
}
}
if(stk.size())
return false;
return true;
}
};