LeetCode 20 Valid Parentheses(用栈判断括号匹配)
来源:互联网 发布:淘宝昵称为什么改不了 编辑:程序博客网 时间:2024/06/05 19:19
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> stk; int len = s.length(); for(int i = 0;i < len;i++){ if(s[i] == '{' || s[i] == '[' || s[i] == '(') { stk.push(s[i]); } else if(stk.size() && isPair(stk.top(), s[i])){ stk.pop(); } else { return false; } } return stk.empty(); }private: bool isPair(char x, char y) { if( (x == '{' && y == '}') || (x == '[' && y == ']') || (x == '(' && y == ')') ){ return true; } else return false; }};
阅读全文
0 0
- LeetCode 20 Valid Parentheses(用栈判断括号匹配)
- LeetCode Valid Parentheses(判断括号是否匹配)
- LeetCode 20 Valid Parentheses 括号匹配问题
- leetcode 20 Valid Parentheses 括号匹配
- LeetCode | Valid Parentheses(括号匹配)
- Valid Parentheses(用栈实现括号匹配)
- 【leetcode】括号符匹配问题(Parentheses):Valid Parentheses|Generate Parentheses|LongestValid Parentheses
- LeetCode | Longest Valid Parentheses(最长有效的括号匹配)
- LeetCode Longest Valid Parentheses 括号匹配
- (leetcode)Valid Parentheses --- 括号匹配问题
- 【LeetCode】 括号匹配1 Valid Parentheses
- 【LeetCode】最长括号匹配Longest Valid Parentheses
- LeetCode-20 Valid Parentheses(判断括号是否规范)
- LeetCode OJ 之 Valid Parentheses(有效的括号判断)
- LeetCode Valid Parentheses判断括号是否配对
- Valid Parentheses --括号匹配
- Valid Parentheses:括号匹配
- 《LeetBook》leetcode题解(20):Valid Parentheses[E]——栈解决括号匹配问题
- 省队集训Round3 DAY2
- Java EE 配置Tomcat
- Android 利用 <activity-alias> 动态改变 App 桌面图标
- POJ1201 Intervals
- leetcode 445. Add Two Numbers II
- LeetCode 20 Valid Parentheses(用栈判断括号匹配)
- HDFS操作-Java接口
- Android跳转到应用商店的APP详情页面,以及 Google GMS 各个apk的包
- android:installLocation简析
- 多线程
- 在linux中使用open函数对文件进行操作后如何读取文件中的内容 lseek fcntl ioctl
- js实现全角半角检测的方法
- 各项技术的总结与分析
- go语言学习之-------go httpserver进阶之路(1)