LeetCode20:Valid Parentheses
来源:互联网 发布:华硕路由器端口转发 编辑:程序博客网 时间:2024/05/19 09:12
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.
Hide Tags Stack String
这道题是检验输入的字符串是否符合规则,因为这是stack里的一道题目,所以一开始就是冲着如何用栈来求解这个问题。
最开始想的是将字符串中的元素全部插入栈中,然后再找出判断规则,很快就发现行不通,因为栈无法进行遍历操作,它只提供有限的几个进栈出栈的函数,然后顺着栈能进行的操作思考是不是在将字符串中的数据入栈的过程中就能进行判断呢?在纸上画了下草图发现真可以,每当遍历到一个元素时将它与栈顶元素进行判断,如果它和栈顶元素匹配,那么将栈顶元素弹出,否则将它入栈。比如说对于输入”([])”,一开始:(“进栈,然后由于”[“与”(“不匹配所以也进栈,然后遍历到”]”,由于”]”与栈顶元素”[“匹配所以”[“出栈,这样一直遍历下去。。。。
runtime:0ms
class Solution {public: bool isValid(string s) { stack<char> datas; for(int i=0;i<s.size();i++) { if(datas.empty()) datas.push(s[i]); else { if(com(datas.top(),s[i])) datas.pop(); else datas.push(s[i]); } } return datas.empty(); } bool com(char lhs,char rhs) { if(lhs=='('&&rhs==')') return true; if(lhs=='['&&rhs==']') return true; if(lhs=='{'&&rhs=='}') return true; return false; }};
在Discuss中看到了另外一种实现,基本思路和我上面也是一样的,但是它的匹配不是像上面定义一个cmp函数,而是通过switch语句进行的,感觉也蛮不错的,所以也按照它的思路实现了一遍:
bool isValid(string s) { stack<int> data; for(int c:s) { switch(c) { case '(': case '[': case '{':data.push(c); break; case ')': { if(data.empty()||data.top()!='(') return false; else { data.pop(); break; } } case ']': { if(data.empty()||data.top()!='[') return false; else { data.pop(); break; } } case '}': { if(data.empty()||data.top()!='{') return false; else { data.pop(); break; } } } } return data.empty(); }
0 0
- LeetCode20: Valid Parentheses
- [LeetCode20]Valid Parentheses
- leetcode20-Valid Parentheses
- LeetCode20:Valid Parentheses
- LeetCode20:Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20 Valid Parentheses
- LeetCode20. Valid Parentheses
- Leetcode20: Valid Parentheses
- Leetcode20. Valid Parentheses
- leetcode20:Valid Parentheses
- LeetCode20. Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20. Valid Parentheses
- 【LeetCode20】【Valid Parentheses】
- Leetcode20. Valid Parentheses
- leetcode20. Valid Parentheses
- LeetCode20. Valid Parentheses
- Java设计模式之责任链模式
- jbtoyjmqme
- leetcode--Binary Tree Maximum Path Sum
- SSL库比较
- Count Complete Tree Nodes
- LeetCode20:Valid Parentheses
- 每个程序员应知晓的编译器优化相关内容(第 2 部分)
- Block的链式编程
- msl、ttl及rtt的区别—— TCP控制字段标志
- 2015.07.10总结
- 解决前台向mysql更新数据的编码问题
- JS返回上一步
- ASP.NET按钮点击后弹出确认提示
- 《Python学习手册》学习笔记——第5章