mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
0020 有效括号增加Java新解法
This commit is contained in:
@ -162,6 +162,33 @@ class Solution {
|
||||
return deque.isEmpty();
|
||||
}
|
||||
}
|
||||
// 方法2
|
||||
class Solution {
|
||||
public boolean isValid(String s) {
|
||||
|
||||
Stack<Character> stack = new Stack<>();
|
||||
Map<Character, Character> map = new HashMap<Character, Character>() {
|
||||
{
|
||||
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:
|
||||
|
Reference in New Issue
Block a user