diff --git a/problems/0020.有效的括号.md b/problems/0020.有效的括号.md index 77c6e10a..98cc7cd8 100644 --- a/problems/0020.有效的括号.md +++ b/problems/0020.有效的括号.md @@ -162,6 +162,33 @@ class Solution { return deque.isEmpty(); } } +// 方法2 +class Solution { + public boolean isValid(String s) { + + Stack stack = new Stack<>(); + Map map = new HashMap() { + { + put('}', '{'); + put(']', '['); + put(')', '('); + } + }; + + for (Character c : s.toCharArray()) { // 顺序读取字符 + if (!stack.isEmpty() && map.containsKey(c)) { // 是右括号 && 栈不为空 + if (stack.peek() == map.get(c)) { // 取其对应的左括号直接和栈顶比 + stack.pop(); // 相同则抵消,出栈 + } else { + return false; // 不同则直接返回 + } + } else { + stack.push(c); // 左括号,直接入栈 + } + } + return stack.isEmpty(); // 看左右是否抵消完 + } +} ``` Python: