0020有效的括号 Java更简单易懂的新解法

This commit is contained in:
Jian
2025-01-08 01:04:07 +08:00
parent b72609d65e
commit d5e0827abe

View File

@ -172,6 +172,29 @@ class Solution {
}
```
```java
// 解法二
// 对应的另一半一定在栈顶
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()){
// 有对应的另一半就直接消消乐
if(c == ')' && !stack.isEmpty() && stack.peek() == '(')
stack.pop();
else if(c == '}' && !stack.isEmpty() && stack.peek() == '{')
stack.pop();
else if(c == ']' && !stack.isEmpty() && stack.peek() == '[')
stack.pop();
else
stack.push(c);// 没有匹配的就放进去
}
return stack.isEmpty();
}
}
```
### Python
```python