forked from Cee/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20 - Valid Parentheses.java
More file actions
29 lines (27 loc) · 834 Bytes
/
20 - Valid Parentheses.java
File metadata and controls
29 lines (27 loc) · 834 Bytes
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
class Solution {
public boolean isValid(String s) {
if (s.length() % 2 != 0) {
return false;
}
Stack<Character> stack = new Stack<>();
for (char c: s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char leftBracket = stack.pop();
if (!isPair(leftBracket, c)) {
return false;
}
}
}
return stack.isEmpty();
}
private boolean isPair(char left, char right) {
return (left == '(' && right == ')') ||
(left == '[' && right == ']') ||
(left == '{' && right == '}');
}
}