标签:leetcode
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是空才对 } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:leetcode
原文地址:http://blog.csdn.net/chibaoneliuliuni/article/details/46756675