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) {
int nLen=s.length();
int i=0;
stack<char> cs;
while(i<nLen)
{
switch(s[i])
{
case '[':
case '{':
case '(':
cs.push(s[i]);
break;
case ']':
{
if(!cs.empty() && cs.top()=='[')
{
cs.pop();
break;
}
else
{
return false;
}
}
case '}':
{
if(!cs.empty() && cs.top()=='{')
{
cs.pop();
break;
}
else
{
return false;
}
}
case ')':
{
if(!cs.empty() && cs.top()=='(')
{
cs.pop();
break;
}
else
{
return false;
}
}
default:
break;
}
++i;
}
if(cs.empty())
{
return true;
}
else
{
return false;
}
}
};