mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
0020有效的括号 Java更简单易懂的新解法
This commit is contained in:
@ -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:
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
Reference in New Issue
Block a user