LeetCode20. Valid Parentheses
来源:互联网 发布:电缆设备负荷计算软件 编辑:程序博客网 时间:2024/06/06 08:42
原题:https://leetcode.com/problems/valid-parentheses/description/
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.
用1,2,3代表三种括号
用一个栈存储左括号,栈顶就是最近的一个左括号,每次遇到右括号时,和栈顶比对,如果匹配则将栈顶pop。如果遇到右括号时栈已空则返回False,匹配完之后栈不为空也返回False。
class Solution {public: bool isValid(string s) { stack<int> last; for (int i = 0; i < s.size(); i++) { if (s[i] == '(') last.push(1); if (s[i] == '[') last.push(2); if (s[i] == '{') last.push(3); if (s[i] == ')') { if (last.empty()||last.top() != 1) { return false; } last.pop(); } if (s[i] == ']') { if (last.empty()||last.top() != 2) { return false; } last.pop(); }if (s[i] == '}') { if (last.empty()||last.top() != 3) { return false; } last.pop(); } } return last.empty(); }};
73 / 73 test cases passed.
Status: Accepted
Runtime: 3 ms
阅读全文
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
- Mysql在linux上使用
- 数据结构与算法分析c++版本学习总结
- 集合扩容
- 你真的会用 CocoaPods 吗?
- Servlet知识总结
- LeetCode20. Valid Parentheses
- okhttp+banner实现自动轮播图
- TCP/IP
- MUI 页面切换时等待动画怎么设置?
- 导航页下拉菜单
- 【论文笔记】Margin Sample Mining Loss: A Deep Learning Based Method for Person Re-identification
- bzoj 1061 [Noi2008]志愿者招募 单纯形算法
- 入门surfaceView实现画图板
- Cassandra