Valid Parentheses:括号匹配
来源:互联网 发布:2016中国网络视频报告 编辑:程序博客网 时间:2024/06/05 13:28
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.
思路:用个栈匹配即可,注意最后若栈不空则不是完全匹配的,同理,若中途栈已空但仍试图匹配括号时,也是不能完全匹配的。
class Solution { public boolean isValid(String s) {Stack<Character> st = new Stack<Character>();for (int i = 0; i < s.length(); i++) {if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[') {st.push(s.charAt(i));}if (s.charAt(i) == ')') {try {char c = st.peek();if (c == '(') {st.pop();} else {return false;}} catch (Exception e) {return false;}}if (s.charAt(i) == ']') {try {char c = st.peek();if (c == '[') {st.pop();} else {return false;}} catch (Exception e) {return false;}}if (s.charAt(i) == '}') {try {char c = st.peek();if (c == '{') {st.pop();} else {return false;}} catch (Exception e) {return false;}}}if (st.isEmpty()){return true;} else {return false;} }}
当然,代码不用这么长,因为只包含括号,所以可以这么写:
public boolean isValid(String s) {Stack<Character> stack = new Stack<Character>();for (char c : s.toCharArray()) {if (c == '(')stack.push(')');else if (c == '{')stack.push('}');else if (c == '[')stack.push(']');else if (stack.isEmpty() || stack.pop() != c)return false;}return stack.isEmpty();}不够匹配或者不能匹配即返回FALSE,还是很省事的。
阅读全文
0 0
- Valid Parentheses --括号匹配
- Valid Parentheses:括号匹配
- 20.Valid Parentheses (括号匹配)
- 多种括号的匹配 Valid Parentheses
- 【栈操作&括号匹配】Valid Parentheses
- LeetCode | Valid Parentheses(括号匹配)
- LeetCode 20 Valid Parentheses 括号匹配问题
- leetcode 20 Valid Parentheses 括号匹配
- Valid Parentheses 合法的括号匹配
- LeetCode Longest Valid Parentheses 括号匹配
- LeetCode Valid Parentheses(判断括号是否匹配)
- 20. Valid Parentheses (括号匹配)
- (leetcode)Valid Parentheses --- 括号匹配问题
- 【LeetCode】 括号匹配1 Valid Parentheses
- 【LeetCode】最长括号匹配Longest Valid Parentheses
- 【leetcode】括号符匹配问题(Parentheses):Valid Parentheses|Generate Parentheses|LongestValid Parentheses
- 寻找最长的括号匹配 Longest Valid Parentheses
- [LeetCode]—Longest Valid Parentheses 最长括号匹配
- 整理一下js判断移动端的各种浏览器
- ubuntu编译安装PHP5.6 ipArchive支持 configure: error: system libzip must be upgraded to version >= 0.11
- TensorFlow--ConfigProto&GPU
- 闭包
- 卡特兰数公式在栈中的应用
- Valid Parentheses:括号匹配
- MySQL高可用架构之MHA
- .NET Core、Xamarin、.NET Standard和.NET Framework四者之间的区别
- 【Java基础】(01)类,继承,接口
- 欢迎使用CSDN-markdown编辑器
- JavaScript模板引擎Template.js使用详解
- android 屏幕分辨率
- 隐式声明与GCC内建函数
- bzoj2440 [中山市选2011]完全平方数(二分答案+莫比乌斯反演)