[C++]LeetCode 20: Valid Parentheses(判断运算符有效性)
来源:互联网 发布:女孩子湿有多夸张知乎 编辑:程序博客网 时间:2024/06/06 03:34
Problem:
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.
分析:
运算符匹配问题,使用stack解决。若是(、[、{,则直接入栈;)、]、}则查看是否匹配,匹配继续查看,不匹配直接返回false。最后若stack为空则配对成功。
AC Code(C++):
注意:开始对s使用的是iterator,结果是10ms,改为下标后为2ms,以后要考虑速度的地方可将iter换为下标
同时,此处只有三组配对,故直接列出,若较多可考虑存储map匹配。
class Solution {public: //65 / 65 test cases passed. //Runtime: 2 ms //开始对s使用的是iterator,结果是10ms,改为下标后为2ms,以后要考虑速度的地方可将iter换为下标 bool isValid(string s) { if (s.size() % 2 == 1) {//奇数个一定invalid return false; } stack<char> pStack; for (int i = 0; i < s.size(); ++i) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') {//直接压入栈 pStack.push(s[i]); } else if (!pStack.empty() && ((s[i] == ')' && pStack.top() == '(') || (s[i] == ']' && pStack.top() == '[') || (s[i] == '}' && pStack.top() == '{'))){//是否可匹配 pStack.pop();//可配对,最顶端出栈 } else{//不可匹配 return false; } } if (pStack.empty()) { return true; } return false; }};
0 0
- [C++]LeetCode 20: Valid Parentheses(判断运算符有效性)
- 【leetcode c++】 20 Valid Parentheses
- LeetCode 20 Valid Parentheses(用栈判断括号匹配)
- LeetCode(20)Valid Parentheses
- LeetCode (20)Valid Parentheses
- [C语言][LeetCode][20]Valid Parentheses
- [C语言][LeetCode][20]Valid Parentheses
- 【leetcode】20. Valid Parentheses(Python & C++)
- 【LeetCode算法练习(C++)】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
- [Leetcode] 20 - Valid Parentheses
- LeetCode | #20 Valid Parentheses
- leetcode.20-----------Valid Parentheses
- 服务器测试工具【Netperf、NetIQ Chariot、NetBench、ServerBench、FileBench、BenchMark Factory等】
- Android核心基础-3.Android 开发环境搭建
- 14 POJ3363 Annoying painting tool
- 石子归并(dp)
- YII2.0 Activeform表单组件的使用方法
- [C++]LeetCode 20: Valid Parentheses(判断运算符有效性)
- UVA - 10820 - Send a Table (欧拉函数)
- struts2学习笔记之一(初识jsp)
- php 判断汉子字母和数字 类型
- IT项目团队管理及领导人素质随记
- 浅谈JAVA设计模式之——建造者模式(Builder)
- 机器视觉代码集合,包括最热门的深度学习代码
- js特效之数码时钟
- PS画菱形并挪出一块