Skip to content

Commit 8eeb2f7

Browse files
committed
Add alternative solution to LC 20 Valid Parenthesis
1 parent e11eddf commit 8eeb2f7

File tree

1 file changed

+31
-1
lines changed

1 file changed

+31
-1
lines changed

20. Valid Parentheses.js

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,11 @@ Constraints:
2828
2929
*/
3030

31-
/**
31+
32+
33+
/**
34+
* Initial solution using if statements
35+
*
3236
* @param {string} s
3337
* @return {boolean}
3438
*/
@@ -44,3 +48,29 @@ const isValid = (s) => {
4448

4549
return stack.length === 0;
4650
};
51+
52+
/**
53+
* Solution using map to match using a hash map to map opening with it's corresponding closing bracket
54+
*
55+
* @param {string} s
56+
* @return {boolean}
57+
*/
58+
const isValidMap = s => {
59+
// Keys are opening brackets and values are it's corresponding closing bracket
60+
const map = {
61+
"(": ")",
62+
"{": "}",
63+
"[": "]",
64+
};
65+
66+
const stack = [];
67+
68+
for (const bracket of s) {
69+
// if bracket is an opening bracket, push it's closing bracket to the stack
70+
if (bracket in map) stack.push(map[bracket]);
71+
// else pop from stack if it's not equal to the current closing bracket return false
72+
else if (stack.pop() !== bracket) return false;
73+
}
74+
75+
return stack.length === 0;
76+
};

0 commit comments

Comments
 (0)