20. 有效的括号
题目:
思路:
【1】无
代码展示:
//时间1 ms 击败 97.94% //内存39.8 MB 击败 23.45% class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); HashMap<Character, Character> check = new HashMap<>(); check.put('(',')'); check.put('{','}'); check.put('[',']'); for (char v : s.toCharArray()){ if (v == '(' || v == '{' || v == '['){ stack.add(v); }else { if (stack.size() > 0 && check.get(stack.pop()) == v){ continue; }else { return false; } } } if (stack.size() > 0) return false; return true; } } //时间0 ms 击败 100% //内存39.6 MB 击败 59.35% class Solution { public boolean isValid(String s) { char[] stack = new char[s.length()]; int top = -1;//栈顶指针 for (char c : s.toCharArray()) { if (c == '(') { stack[++top] = ')'; } else if (c == '[') { stack[++top] = ']'; } else if (c == '{') { stack[++top] = '}'; } else if (top == -1 || stack[top--] != c) {//之前没有对应的左括号或者左右括号不匹配 return false; } } return top == -1;//判断是否有剩余的左括号没有被匹配 } }