20. Valid Parentheses
来源:互联网 发布:linux启动ftp服务 编辑:程序博客网 时间:2024/06/05 17:59
每次遇到valid parenthesis的题目,就想到stack的结构来存储,因为判断这个左右匹配的题型涉及到,当前字符和之前字符的读取,所以需要stack来存储之前的数据。。。
代码如下,再自己实现一遍:
public class Solution { public boolean isValid(String s) {/* if(s==null || s.length()==0) return false; else{ Map<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++){ if(map.containsKey(s.charAt(i))) stack.push(s.charAt(i)); else{ //!map.containsKey(s.charAt(i))) if(stack.isEmpty()) return false; else if(map.get(stack.pop().charValue())!=s.charAt(i)) return false; } //char charValue() Returns the value of this Character object. } if(stack.empty()) return true; else return false; // 以上两句可改写为: return stack.empty(); 然后还发现 empty() 和 isEmpty() 是不同的名字同一个函数*/ // 以上是1月初左右写的。以下是第二次,1.29写的 if(s==null || s.equals("")) return false;Stack<Character> stack= new Stack<Character>();for(char ch: s.toCharArray()){if(ch=='(' || ch=='[' || ch=='{') stack.push(ch);else if (ch==')' && (stack.isEmpty() || stack.pop()!='(' )) return false; else if (ch==']' && (stack.isEmpty() || stack.pop()!='[' )) return false;else if (ch=='}' && (stack.isEmpty() || stack.pop()!='{' )) return false;}return stack.isEmpty(); }}
今天的代码,略为简单点,在细节的处理上
public class Solution { public boolean isValid(String s) { if(s.equals("")) return false; // 这个是必须的,因为最好要通过stack.isEmpty()来判断,但是如果是“”那么就应该return falase Stack<Character> stack = new Stack<Character>(); for(char ch: s.toCharArray()){ // 思路:遍历string,分两大类考虑,左边类和右边类:左边,push,右边的话,就要判断了。。 if(ch=='(' || ch=='[' || ch=='{') stack.push(ch); else if(ch==')' || ch==']' || ch=='}'){ if(stack.isEmpty()) return false; else{ if(ch==')' && stack.peek()!='(' || ch==']' && stack.peek()!='[' || ch=='}' && stack.peek()!='{' ) return false; } stack.pop(); } } return stack.isEmpty()?true:false; }}
0 0
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 20.Valid Parentheses
- 20.Valid Parentheses
- 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- 20. Valid Parentheses
- 20. Valid Parentheses
- 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- 20. Valid Parentheses
- 20. Valid Parentheses
- 登陆oracle的三种方法
- 290. Word Pattern
- vim moving
- vim separate with . and replace all to end of line
- java多态
- 20. Valid Parentheses
- 292. Nim Game
- vim delete all blank lines
- Leetcode 86. Partition List
- linux count file lines
- linux split files according lines number
- uva11520 填充正方形
- 21. Merge Two Sorted Lists
- LaTeX: two figures in one line (两个图片置于同一行)