您的位置:首页 > 其它

LeetCode *** 20. Valid Parentheses

2016-04-10 10:36 393 查看
题目:

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) {

stack<char> myStk;

for(int i=0;i<s.length();++i){
if(s[i]=='('||s[i]=='{'||s[i]=='['){
myStk.push(s[i]);
}
else{
if(myStk.empty())return false;
char top=myStk.top();
myStk.pop();
if(!((top=='('&&s[i]==')')||(top=='['&&s[i]==']')||(top=='{'&&s[i]=='}')))return false;
}
}

return myStk.empty();

}
};

错误代码:

class Solution {
public:
bool isValid(string s) {
int test1=0,test2=0,test3=0;

if(s.length()%2)return false;

for(int i=0;i<s.length();++i){
switch(s[i]){
case '(':test1+=1;break;
case ')':test1-=1;break;
case '{':test2+=1;break;
case '}':test2-=1;break;
case '[':test3+=1;break;
case ']':test3-=1;break;
}
if(test1<0||test2<0||test3<0)return false;
if(test1>0){
if(test2||test3)return false;
}
if(test2>0){
if(test1||test3)return false;
}
if(test3>0){
if(test1||test2)return false;
}
}

if(!test1&&!test2&&!test3)return true;
else return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: