leetcode-Valid Parentheses

来源:互联网 发布:老男孩 python 12期 编辑:程序博客网 时间:2024/06/05 13:34

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.

思路:利用栈结构,将左括号入栈,当遇到右括号,出栈判断是否匹配。最后栈为空则括号匹配

代码:

bool isValid(string s) {
        string stack;
int len=s.length();
if(len<1)
{
return true;
}
if(len&0x0001 == 1)
{
return false;
}
int i=0;
int lenOfStack=0;
while(i<len)
{
if(s[i] == '(' || s[i]=='[' || s[i]=='{')
{
stack[lenOfStack]=s[i];
++lenOfStack;
++i;
}
else if(s[i] == ')')
{
if(stack[lenOfStack-1]=='(')
{
--lenOfStack;
++i;
}
else
{
return false;
}
}
else if(s[i] == ']')
{
if(stack[lenOfStack-1]=='[')
{
--lenOfStack;
++i;
}
else
{
return false;
}
}
else if(s[i] == '}')
{
if(stack[lenOfStack-1]=='{')
{
--lenOfStack;
++i;
}
else
{
return false;
}
}
}
if(lenOfStack == 0)
{


return true;
}
else
{
return false;
}
    }

0 0