LeetCode--No.20--Valid Parentheses
来源:互联网 发布:星际淘宝网笔下 编辑:程序博客网 时间:2024/05/17 07:05
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.
Subscribe to see which companies asked this question
注意:
1. HashMap 声明时可以注明格式
2. String 可以求长度。String.length()
3. String 可以去某一个值作为Char s.charAt(i)
4. Stack的使用
代码转载自:http://www.programcreek.com/2012/12/leetcode-valid-parentheses-java/ 侵删
public class Solution { public boolean isValid(String s) { HashMap<Character, Character> map = new HashMap<Character, Character>(); map.put('(',')'); map.put('[',']'); map.put('{','}'); Stack<Character> stack = new Stack<Character>(); for(int i = 0; i < s.length(); i++){ char curr = s.charAt(i); if(map.keySet().contains(curr)){ stack.push(curr); }else if(map.values().contains(curr)){ if(!stack.empty() && map.get(stack.peek()) == curr){ stack.pop(); }else{ return false; } } } return stack.empty(); }}
按照自己的思路重新写了一下,但是借鉴了一些上面的java语法:
public class Solution { public boolean isValid(String s) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); map.put('(',1); map.put('[',2); map.put('{',3); map.put(')',-1); map.put(']',-2); map.put('}',-3); Stack<Integer> stack = new Stack<Integer>(); for(int i = 0; i < s.length(); i++){ char curr = s.charAt(i); int temp = map.get(curr); if(temp > 0){ stack.push(temp); } else{ if (!stack.empty() && (stack.peek() + temp == 0)) stack.pop(); else return false; } } return stack.empty(); }}
这里要注意的是: 记得判断 stack.empty()
不然直接取stack.peek()会报错
0 0
- Leetcode NO.20 Valid Parentheses
- LeetCode--No.20--Valid Parentheses
- LeetCode No.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
- 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
- 网络编程学习笔记一:Socket编程
- 如何在Java中构造多维动态数组以及多维动态数组的使用
- HDU 3974 Assign the task(并查集)
- Spring集成Shiro HelloWorld之初步实现登陆及验证
- hadoop机架感知
- LeetCode--No.20--Valid Parentheses
- 机器学习这么火,想跳坑该怎么做?
- 陶哲轩实分析-第18章 Lebesgue积分
- Implement Stack using Queues
- 【日志7.13】
- Meta http-equiv属性详解
- LeetCode--No.38--Count and Say
- LeetCode--No.58--Length of Last Word
- 网络爬虫项目开发日志(一):关于爬虫项目所涉及的领域知识