#leetcode#Valid Parentheses
来源:互联网 发布:阿里云 域名 编辑:程序博客网 时间:2024/06/15 11:51
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.
这题并不难, 但是还是暴露出几个问题:
1)stack.peek()之前没有判断 是否stack.isEmpty()
2) 最后直接return true了,其实应该return stack是否为空
另外用switch写的有点繁琐, 代码重复, 应该可以更精简一些
public class Solution { public boolean isValid(String s) { if(s == null || s.length() % 2 == 1){ return false; } LinkedList<Character> stack = new LinkedList<Character>(); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(c == '(' || c == '[' || c == '{'){ stack.push(c); }else{ switch(c){ case ')' : if(!stack.isEmpty()){ // 一定要先判断stack是否empty if(stack.peek() != '('){ return false; }else{ stack.pop(); } }else{ return false; } break; case ']': if(!stack.isEmpty()){ if(stack.peek() != '['){ return false; }else{ stack.pop(); } }else{ return false; } break; case '}': if(!stack.isEmpty()){ if(stack.peek() != '{'){ return false; }else{ stack.pop(); } }else{ return false; } break; default : return false; } } } // return true; return stack.isEmpty(); //最后应该所有括号都成对, 所以stack是空才对 } }
优化一下上面丑陋的代码。。
public class Solution { public boolean isValid(String s) { if(s == null || s.length() % 2 == 1){ return false; } LinkedList<Character> stack = new LinkedList<Character>(); for(int i = 0; i < s.length(); i++){ char c = s.charAt(i); if(c == '(' || c == '[' || c == '{'){ stack.push(c); }else{ if(stack.isEmpty()){ return false; } char pre = stack.pop(); switch(c){ case ')' : if(pre != '(') return false; break; case ']': if(pre != '[') return false; break; case '}': if(pre != '{') return false; break; default : return false; } } } // return true; return stack.isEmpty(); //最后应该所有括号都成对, 所以stack是空才对 } }
0 0
- LeetCode: Valid Parentheses
- LeetCode: Longest Valid Parentheses
- LeetCode: Valid Parentheses
- LeetCode Longest Valid Parentheses
- [Leetcode] Valid Parentheses
- LeetCode: Longest Valid Parentheses
- [Leetcode] Longest Valid Parentheses
- LeetCode : Valid Parentheses
- [leetcode]longest Valid Parentheses(!!)
- Leetcode: Valid Parentheses
- leetcode 52: valid parentheses
- [Leetcode] Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- 【leetcode】Valid Parentheses
- 【leetcode】Longest Valid Parentheses
- [LeetCode]Longest Valid Parentheses
- [LeetCode]Valid Parentheses
- LeetCode-Valid Parentheses
- 简单流程测试(部署到审核)(2)
- C3_循环结构练习
- zepto在安卓下使用swipe, swipeLeft, swipeRight 无效解决
- 浅析Context及可能带来的内存泄漏问题(转载)
- LTE中的SPS
- #leetcode#Valid Parentheses
- 集成FUSE的程序在后台运行后,创建的多个线程被自动杀死!
- ListView中隐藏输入法键盘
- java 保留2位小数
- GCC系列: __attribute__((visibility("")))
- [素材]pchome左侧有奖调查
- 每天学一点3
- 找出字符串中第1个只出现1次的字符
- 从坷里化理解Py带参数的decorator