forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0020-valid-parentheses.java
50 lines (44 loc) · 1.58 KB
/
0020-valid-parentheses.java
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
40
41
42
43
44
45
46
47
48
49
50
class Solution {
public boolean isValid(String s) {
if (s.length() % 2 != 0) return false;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (
stack.isEmpty() &&
(s.charAt(i) == ')' || s.charAt(i) == '}' || s.charAt(i) == ']')
) return false; else {
if (
s.charAt(i) == ')' && stack.peek() == '('
) stack.pop(); else if (
s.charAt(i) == '}' && stack.peek() == '{'
) stack.pop(); else if (
s.charAt(i) == ']' && stack.peek() == '['
) stack.pop(); else stack.add(s.charAt(i));
}
}
return stack.isEmpty();
}
}
//Solution with HashMap Lookup table as described in the video
class Solution {
public boolean isValid(String s) {
Stack<Character> brackets = new Stack<>();
Map<Character, Character> bracketLookup = new HashMap<>(3);
bracketLookup.put(')', '(');
bracketLookup.put('}', '{');
bracketLookup.put(']', '[');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (bracketLookup.containsKey(c)) {
if (!brackets.isEmpty() && bracketLookup.get(c).equals(brackets.peek())) {
brackets.pop();
} else {
return false;
}
} else {
brackets.push(c);
}
}
return brackets.isEmpty();
}
}