-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution20.java
More file actions
30 lines (26 loc) · 850 Bytes
/
Copy pathsolution20.java
File metadata and controls
30 lines (26 loc) · 850 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
import java.util.HashMap;
import java.util.Stack;
public class solution20 {
private HashMap<Character,Character> mappings;
public solution20(){
this.mappings = new HashMap<Character,Character>();
this.mappings.put(')','(');
this.mappings.put('}','{');
this.mappings.put(']','[');
}
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (this.mappings.containsKey(c)) {
char topElement = stack.empty() ? '#' : stack.pop();
if (topElement != this.mappings.get(c)) {
return false;
}
} else {
stack.push(c);
}
}
return stack.isEmpty();
}
}