【LeetCode】20_Valid Parentheses
来源:互联网 发布:极光丛林果汁 淘宝 编辑:程序博客网 时间:2024/05/22 08:08
题目
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.
解析
就是用堆栈来做。碰到[]对这种就出栈。
我刚开始以为只能是{}[]()这种,所以做了一个每次有(,[,{的时候就判断是否为空,不为空则false。后来它的案例中也有{()}这种,可见不用做这个判断。
我的代码如下
class Solution {public: bool isValid(string s) { stack<char> st;//string::iterator point;for (int i = 0;i<s.size();i++){if (s[i] == ')'){if(!st.empty() &&st.top() == '('){st.pop();}else{return false;}}else if (s[i] == ']'){if(!st.empty() &&st.top() == '['){st.pop();}else{return false;}}else if (s[i] == '}'){if(!st.empty() &&st.top() == '{'){st.pop();}else{return false;}}if (s[i]=='(' || s[i]=='[' || s[i]=='{'){st.push(s[i]);}}if (st.empty()){return true;}else{return false;} }};
在参照别人的代码后,发现自己代码实在有点杂乱,改正优化后如下
class Solution {public: bool isValid(string s) {stack<char> st;//string::iterator point;for (int i = 0;i<s.size();i++){if (s[i] == ')' || s[i] == ']' || s[i] == '}'){if (st.empty())return false;else if((st.top() == '(' && s[i] == ')') || (st.top() == '[' && s[i] == ']')||(st.top() == '{' && s[i] == '}'))st.pop();elsereturn false;}if (s[i]=='(' || s[i]=='[' || s[i]=='{')st.push(s[i]);}if (st.empty())return true;elsereturn false; }};
简洁多了。
再来看看大神的代码
class Solution {public: bool isValid(string s) { string left = "([{"; string right = ")]}"; stack<char> stk; for (auto c : s) { if (left.find(c) != string::npos) { stk.push (c); } else { if (stk.empty () || stk.top () != left[right.find (c)]) return false; else stk.pop (); } } return stk.empty();}};
大神的方法思路基本就是用两个对应的字符串,到时候去找相同的位置就可以把(){}[]进行匹配。
值得注意的是最后的return stk.empty();实在省事多了啊。
最后总结一下stack的用法吧,图片来自http://blog.csdn.net/morewindows/article/details/6950881
0 0
- 【LeetCode】20_Valid Parentheses
- LeetCode 20_Valid Parentheses
- [LeetCode]20_Valid Parentheses
- leetcode 019_Valid Parentheses
- leetcode第一刷_Valid Parentheses
- 20_Valid Parentheses徒手尝试#2(Done)
- 0020_Valid Parentheses
- 【LeetCode】125_Valid Palindrome
- leetcode第一刷_Valid Palindrome
- leetcode第一刷_Valid Number
- leetcode第一刷_Valid Sudoku
- LeetCode 20: Valid Parentheses
- LeetCode(20) Valid Parentheses
- leetcode 20 Valid Parentheses
- Leetcode【20】:Valid Parentheses
- leetcode 20-Valid Parentheses
- [leetcode 20] Valid Parentheses
- [Leetcode] 20 - Valid Parentheses
- 第10章 JSP、JavaBean和Servlet的配合使用
- druid简单教程
- 长连接
- Spring整合JMS——基于ActiveMQ实现
- Struts2拦截器篇(一)
- 【LeetCode】20_Valid Parentheses
- 数组笔记
- hiho一下 第五十九周 Performance Log
- 在windows添加视图
- Android 高手进阶之自定义View,自定义属性(带进度的圆形进度条)
- poj1599
- [LeetCode] Group Anagrams
- ubuntu 取色软件 Gpick
- POJ1988 Cube Stacking