LeetCode *** 20. Valid Parentheses
2016-04-10 10:36
393 查看
题目:
Given a string containing just the characters
The brackets must close in the correct order,
分析:
一开始题目理解错了。。于是乎。。。把一个错误的代码改了几遍才发现自己错了。。吐血。。。这个题用栈做。
代码:
错误代码:
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; } };
相关文章推荐
- WebView.HitTestResult
- 一般图的匹配题集
- 第七周 项目2 友元类
- 羡慕从来不发朋友圈的人,因为...
- 对话框输入输出
- nyoj860 又见01背包
- 做完VB后的感言
- C++需要注意的地方
- openlayer 3 长按事件
- 团队作业 团队组织方式讨论
- 第七周 项目1-成员函数、友元函数和一般函数有区别(1)一般
- JFileChooser 如何保存上次打开文件时的路径
- DirectX的Vertex Buffer顶点缓冲的理解和应用
- 入门第一周项目一—温度转换程序
- Dancing Links题集
- hdu--1716--排列2
- 第七周 项目1-成员函数、友元函数和一般函数有区别(1)外部
- webservice soap WSDL中的tns字段什么意思?
- 如何模块化的组织AngularJS的代码
- 按之字形顺序打印二叉树