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 "([)]"
are not.
class Solution
{
public:
bool isValid(string s)
{
int len = s.length();
string stack(len,' ');
int j = -1;
for(int i=0; i<len; i++)
{
//左括号,则入栈
if(s[i]=='(' || s[i]=='[' || s[i]=='{')
{
j++;
stack[j] = s[i];
}
//右括号,则出栈一个元素与之对比
if(s[i]==')' || s[i]==']' || s[i]=='}')
{
if(j < 0) //栈为空
return false;
if((stack[j]=='('&&s[i]!=')')||(stack[j]=='['&&s[i]!=']')||(stack[j]=='{'&&s[i]!='}'))
return false;
else
j--;
}
}
if(j >= 0) //左括号还有剩余
return false;
else
return true;
}
};