[LeetCode]--20. Valid Parentheses
来源:互联网 发布:网络授权书制作免费 编辑:程序博客网 时间:2024/05/17 09:27
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.
public boolean isValid(String s) { if (s.length() % 2 != 0) return false; char[] characters = new char[s.length()]; int index = 0, i; for (i = 0; i < s.length(); i++) { if (s.charAt(i) == '(') characters[index++] = s.charAt(i); if (s.charAt(i) == '[') characters[index++] = s.charAt(i); if (s.charAt(i) == '{') { characters[index++] = s.charAt(i); System.out.println(index); } if (s.charAt(i) == ')') { if (--index < 0 || characters[index] != '(') break; } if (s.charAt(i) == ']') { if (--index < 0 || characters[index] != '[') break; } if (s.charAt(i) == '}') { if (--index < 0 || characters[index] != '{') break; } } if (i == s.length() && index == 0) return true; return false; }
方法通过了,不过觉得有点笨,暂时也没想到好的,先就这样啦。LeedCode也没给我们提供详解。
找到一个写得比较好的程序,极力推荐大家不要看我的,看这个,又感觉被甩了几条街。
public boolean isValidParentheses(String s) { Stack<Character> stack = new Stack<Character>(); for (Character c : s.toCharArray()) { if ("({[".contains(String.valueOf(c))) { stack.push(c); } else { if (!stack.isEmpty() && is_valid(stack.peek(), c)) { stack.pop(); } else { return false; } } } return stack.isEmpty(); } private boolean is_valid(char c1, char c2) { return (c1 == '(' && c2 == ')') || (c1 == '{' && c2 == '}') || (c1 == '[' && c2 == ']'); }
用了系统的栈,我用的数组栈。
0 0
- 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
- 20. Valid Parentheses LeetCode
- 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
- 随机访问流:
- 以首字母开头的所有汉字组合
- OpenCV图像旋转算法
- 实验楼Linux学习笔记(十二)之软件安装管理
- Atitit 编程语言原理与概论attilax总结
- [LeetCode]--20. Valid Parentheses
- Lock锁学习
- Programming In Scala笔记-第八章、函数与闭包
- Atitit.并发编程原理与概论 attilax总结
- 【Linux4.1.12源码分析】二层报文发送之GSO条件判断
- Java实现验证码(上)
- 自定义控件系列<第一篇>--多维表头
- 面向对象设计原则——单一职责原则(SRP)
- 泛型接口的使用