标签:stack实现 The 最快 stat lis rac cte style sem
class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); HashSet<Character> set = new HashSet<>(Arrays.asList(‘[‘,‘{‘,‘(‘)); for(int i=0;i<s.length();i++){ char parenthese = s.charAt(i); if(set.contains(parenthese)){ stack.push(parenthese); } else{ if(stack.isEmpty()) return false; char left = stack.pop(); if((left==‘(‘&&parenthese!=‘)‘)||(left==‘[‘&&parenthese!=‘]‘)||(left==‘{‘&&parenthese!=‘}‘)){ return false; } } } if(stack.isEmpty()){ return true; } else return false; } }
8ms和12ms,末流。
简化了一下代码,依旧很慢。
class Solution { private static final HashMap<Character,Character> map = new HashMap<Character,Character>(){ { put(‘(‘,‘)‘);put(‘{‘,‘}‘);put(‘[‘,‘]‘); } }; public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for(int i=0;i<s.length();i++){ char p = s.charAt(i); if(map.keySet().contains(p)){ stack.push(map.get(p)); } else{ if(stack.isEmpty()) return false; char right = stack.pop(); if(p!=right){ return false; } } } if(stack.isEmpty()) return true; else return false; } }
10ms,14ms,看看别人的吧。
看了最快的3ms方法,是使用了数组代替stack实现,所以会快一些。自己尝试一遍吧。
public static boolean isValid(String s) { char[] stack = new char[s.length()]; int stackTop = -1; for(int i=0;i<s.length();i++){ char p = s.charAt(i); if(p==‘(‘||p==‘{‘||p==‘[‘){ stack[++stackTop]=p; } else{ if(stackTop<0) return false; if(p==‘)‘) { if(stack[stackTop--]!=‘(‘) return false;} else if(p==‘]‘) { if(stack[stackTop--]!=‘[‘) return false;} else if(p==‘}‘) { if(stack[stackTop--]!=‘{‘) return false;} } } if(stackTop>=0) return false; else return true; }
可以了。然后记录个容易出bug的写法,我之前上面这段是这么写的
if(stackTop<0) return false; if(p==‘)‘) if(stack[stackTop--]!=‘(‘) return false; else if(p==‘]‘) if(stack[stackTop--]!=‘[‘) return false; else if(p==‘}‘) if(stack[stackTop--]!=‘{‘) return false;
乍一看没啥毛病对吧,但是咋跑咋不对,只能跑出()是对的,{}[]都是false。咋回事儿呢?
因为,这样写的话,编译器会把第一个else if 归为
if(stack[stackTop--]!=‘(‘)
的else if…
数组代替stack的方法值得重新刷一遍。
标签:stack实现 The 最快 stat lis rac cte style sem
原文地址:https://www.cnblogs.com/chason95/p/10095658.html