-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode20.java
More file actions
36 lines (33 loc) · 1.01 KB
/
LeetCode20.java
File metadata and controls
36 lines (33 loc) · 1.01 KB
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
import java.util.Stack;
import java.util.HashMap;
public class LeetCode20 {
public static void main(String[] args) {
System.out.println(new Solution20().isValid("()"));
System.out.println(new Solution20().isValid("()[]{}"));
System.out.println(new Solution20().isValid("(]"));
}
}
class Solution20 {
public boolean isValid(String s) {
if (s.length() % 2 == 1) {
return false;
}
Stack<Character> stack = new Stack<>();
HashMap<Character, Character> dict = new HashMap<>();
dict.put(')', '(');
dict.put(']', '[');
dict.put('}', '{');
for (int i = 0; i < s.length(); i++) {
Character ch = s.charAt(i);
if (dict.containsKey(ch)) {
if (stack.isEmpty() || stack.peek() != dict.get(ch)) {
return false;
}
stack.pop();
} else {
stack.push(ch);
}
}
return stack.isEmpty();
}
}