Skip to content

Commit

Permalink
Update 0020-valid-parentheses.java
Browse files Browse the repository at this point in the history
Added additional solution which implements a HashMap to store a lookup table of brackets to check the solution.
  • Loading branch information
OfficialTomJ authored Feb 4, 2023
1 parent f12771c commit d0b908f
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions java/0020-valid-parentheses.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,31 @@ public boolean isValid(String s) {
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<>();

bracketLookup.put(')', '(');
bracketLookup.put('}', '{');
bracketLookup.put(']', '[');

for (char c : s.toCharArray()) {
if (bracketLookup.containsKey(c)) {
if (brackets.size() != 0 && brackets.peek() == bracketLookup.get(c)) {
brackets.pop();
} else {
return false;
}
} else {
brackets.push(c);
}
}

if (brackets.size() == 0) return true;
return false;
}
}

0 comments on commit d0b908f

Please sign in to comment.