20. Valid Parentheses(stack)
2016-01-27 13:16
295 查看
Given a string containing just the characters
The brackets must close in the correct order,
public class Solution {
'(',
')',
'{',
'}',
'['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 class Solution {
if (s == null) return false; Stack<Character> stack = new Stack<Character>(); char[] ch = s.toCharArray(); for (int i = 0; i < ch.length; i++) { if ((ch[i] == '(') || (ch[i] == '[') || (ch[i] == '{')) stack.push(ch[i]); else { if (stack.isEmpty()) return false; if (ch[i] - stack.pop() > 2) return false; } } return stack.isEmpty();
public boolean isValid(String s) { if (s == null) //改进1:可以不用String.charat(i) return false; //改进2: 先判断长度 //改进三: 不需要这么多if else ,符号的判断可以用ascii码 Stack<Character> stack = new Stack<Character>(); char[] ch = s.toCharArray(); for (int i = 0; i < ch.length; i++) { if ((ch[i] == '(') || (ch[i] == '[') || (ch[i] == '{')) stack.push(ch[i]); else { if (ch[i] == ')') { if (stack.isEmpty()) return false; else if (stack.pop() != '(') return false; } if (ch[i] == ']') { if (stack.isEmpty()) return false; if (stack.pop() != '[') return false; } if (ch[i] == '}') { if (stack.isEmpty()) return false; if (stack.pop() != '{') return false; } } } if (!stack.isEmpty()) return false; else return true; } }
相关文章推荐
- How to overlay an icon over existing shell objects
- 重载操作符??
- Erlang与java的内存架构比较
- 用Pandas完成Excel中常见的任务
- window.onerror()的用法与实例分析
- Apktool反编译错误问题解决方法
- 黑马程序员——java数组
- Linux配置系统
- iOS UIWebview仿微信进度条
- 【C++】 一维数组的初始化
- 杭电2017
- CSU 1228 ACM小组的数字游戏
- 说说自己常用的jdk包?
- MFC定时器的使用
- MD5加密
- leptus和cowboy之间某些库的转换
- mysql执行show processlist unauthenticated user 解决方法
- the path to become a better android developer is starting up
- ThinkPHP关联模型
- 234,SDWebImage的使用