您的位置:首页 > 其它

[leetcode]20. Valid Parentheses

2016-12-29 16:30 351 查看
class Solution {
public:
bool isValid(string s) {
int length=s.length();
if(length==0) return true;
if(length%2 != 0) return false;

char flag[6]={'(',')','{','}','[',']'};
stack<char> a;
a.push(s[0]);

for(int i=1; i<length; i++)
{
if(a.empty())
a.push(s[i]);
else
{
char tmp = a.top();
if( ((tmp==flag[0])&&(s[i]==flag[1])) || ((tmp==flag[2])&&(s[i]==flag[3])) || ((tmp==flag[4])&&(s[i]==flag[5])) )
a.pop();
else
a.push(s[i]);
}
}

if(a.empty())
return true;
else
return false;
}
};

Given a string containing just the characters '(',')','{','}','[',']', determine if the input string is valid.
The brackets must close in the correct order,"()" and "()[]{}" are all valid but "(]" and "([)]" are not valid

最开始看到这个问题以为是规律给出来的,比如说是这样的:(){}[](),这样的理解是不对的,([])这样的结果也是对的

所以,用栈这种数据结构来处理这种问题是最方便的,代码如下
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: