Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d5e0827

Browse files
0020有效的括号 Java更简单易懂的新解法
1 parent b72609d commit d5e0827

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

‎problems/0020.有效的括号.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,29 @@ class Solution {
172172
}
173173
```
174174

175+
```java
176+
// 解法二
177+
// 对应的另一半一定在栈顶
178+
class Solution {
179+
public boolean isValid(String s) {
180+
Stack<Character> stack = new Stack<>();
181+
for(char c : s.toCharArray()){
182+
// 有对应的另一半就直接消消乐
183+
if(c == ')' && !stack.isEmpty() && stack.peek() == '(')
184+
stack.pop();
185+
else if(c == '}' && !stack.isEmpty() && stack.peek() == '{')
186+
stack.pop();
187+
else if(c == ']' && !stack.isEmpty() && stack.peek() == '[')
188+
stack.pop();
189+
else
190+
stack.push(c);// 没有匹配的就放进去
191+
}
192+
193+
return stack.isEmpty();
194+
}
195+
}
196+
```
197+
175198
### Python:
176199

177200
```python

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /