-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL00020.java
More file actions
33 lines (31 loc) · 891 Bytes
/
L00020.java
File metadata and controls
33 lines (31 loc) · 891 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
30
31
32
33
package leetcode;
import java.util.*;
public class L00020 {
public boolean isValid(String s) {
HashMap<Character, Character> pairs = new HashMap<>() {{
put(')', '(');
put('}', '{');
put(']', '[' );
}};
List<Character> openers = new ArrayList<>() {{
add('(');
add('{');
add('[');
}};
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (openers.contains(c)) {
stack.push(c);
} else {
if (stack.contains(pairs.get(c))) {
if (pairs.get(c) != stack.peek())
return false;
stack.pop();
} else {
return false;
}
}
}
return stack.isEmpty();
}
}