20. Valid Parentheses

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
class Solution {
public boolean isValid(String s) {
if ((s.length() & 1) != 0) {
return false;
}

Stack<Character> stack = new Stack<>();

for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '(':
case '{':
case '[':
stack.push(c);
break;
case ')':
if (stack.isEmpty() || stack.pop() != '(') {
return false;
}
break;
case '}':
if (stack.isEmpty() || stack.pop() != '{') {
return false;
}
break;
case ']':
if (stack.isEmpty() || stack.pop() != '[') {
return false;
}
break;
default:
throw new IllegalArgumentException("Unsupported char: " + c);
}
}

return stack.isEmpty();
}
}

References

20. Valid Parentheses