LeetCode 20 有效的括號
阿新 • • 發佈:2020-08-14
LeetCode 20 有效的括號
給定一個代表包含一系列括號{}、[]、()
的字串,判斷該字串是否是一個合法的字串(同類型左右括號匹配,且必須是連續的)
輔助棧
class Solution { public boolean isValid(String s) { if(s==null || s.length()==0) return true; /*存在先後順序的情況使用棧來判斷*/ List<Character> stack = new ArrayList<>(); int top = -1; for(int i=0;i<s.length();i++){ char ch = s.charAt(i); switch(ch) { case '(': case '{': case '[': { stack.add(ch);top++; break; } case ')': { if(top>-1 && stack.get(top)=='('){ stack.remove(top);top--; break; } return false; } case '}': { if(top>-1 && stack.get(top)=='{'){ stack.remove(top);top--; break; } return false; } case ']': { if(top>-1 && stack.get(top)=='['){ stack.remove(top);top--; break; } return false; } } } if(top!=-1) return false; else return true; } }