-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20.有效的括号.java
42 lines (38 loc) · 1.06 KB
/
20.有效的括号.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
* @lc app=leetcode.cn id=20 lang=java
*
* [20] 有效的括号
*/
// @lc code=start
class Solution {
public boolean isValid(String s) {
if (s.length() == 0) return true;
if ((s.length() & 1) == 1) return false;
Stack<Character> leftStack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '(':
leftStack.push(')');
break;
case '{':
leftStack.push('}');
break;
case '[':
leftStack.push(']');
break;
default:
if (
!leftStack.isEmpty() &&
leftStack.peek().equals(s.charAt(i))
) {
leftStack.pop();
} else {
return false;
}
break;
}
}
return leftStack.isEmpty();
}
}
// @lc code=end