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;
}
};