Leet Code 20 Valid Parentheses
2015-09-12 03:08
323 查看
Given a string containing just the characters
determine if the input string is valid.
The brackets must close in the correct order,
all valid but
not.
【算法思路】
用栈。
'(',
')',
'{',
'}',
'['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) { int length = s.length(); if(length % 2 == 1) { return false; } HashMap<Character, Character> map = new HashMap<Character, Character>(); map.put('(', ')'); map.put('{', '}'); map.put('[', ']'); Stack<Character> stack = new Stack<Character>(); if(map.containsKey(s.charAt(0))) stack.push(s.charAt(0)); else return false; for(int i = 1; i < length; i ++) { char ch = s.charAt(i); if(!stack.isEmpty() && (map.get(stack.peek()) == ch)) { stack.pop(); } else if(map.containsKey(ch)) stack.push(ch); else return false; if(!stack.isEmpty() && (stack.size() > length - i)) return false; } return stack.isEmpty(); }
相关文章推荐
- LeetCode Triangle
- Leet Code 19 Remove Nth Node From End of List
- 常见安卓主题显示
- Leet Code Medium 18 4Sum
- 【小熊刷题】3Sum Closest <Leetcode 16, Java>
- Part 98 Anonymous methods in c#
- 八大排序算法
- 教你如何迅速秒杀掉:99%的海量数据处理面试题
- 学长们的求职血泪史(C/C++/JAVA)
- Majority Element II
- 计票统计
- 设计模式交流会总结
- Zabbix 监控 Nginx
- Flash Stage3D 在2D UI 界面上显示3D模型问题完美解决
- POJ 2155 解题报告
- Effective C++ 条款46 需要类型转换时请为模板定义非成员函数
- Codeforces Round #319 (Div. 2)(A,B,C,E)
- 使用ngx_lua构建高并发应用
- HYSBZ 1492 Cash(CDQ分治论文题)
- mongodb副本集群搭建