Skip to content

Commit d0b908f

Browse files
authored
Update 0020-valid-parentheses.java
Added additional solution which implements a HashMap to store a lookup table of brackets to check the solution.
1 parent f12771c commit d0b908f

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

java/0020-valid-parentheses.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,31 @@ public boolean isValid(String s) {
2222
return stack.isEmpty();
2323
}
2424
}
25+
26+
//Solution with HashMap Lookup table as described in the video
27+
28+
class Solution {
29+
public boolean isValid(String s) {
30+
Stack<Character> brackets = new Stack<>();
31+
Map<Character, Character> bracketLookup = new HashMap<>();
32+
33+
bracketLookup.put(')', '(');
34+
bracketLookup.put('}', '{');
35+
bracketLookup.put(']', '[');
36+
37+
for (char c : s.toCharArray()) {
38+
if (bracketLookup.containsKey(c)) {
39+
if (brackets.size() != 0 && brackets.peek() == bracketLookup.get(c)) {
40+
brackets.pop();
41+
} else {
42+
return false;
43+
}
44+
} else {
45+
brackets.push(c);
46+
}
47+
}
48+
49+
if (brackets.size() == 0) return true;
50+
return false;
51+
}
52+
}

0 commit comments

Comments
 (0)