File tree Expand file tree Collapse file tree 1 file changed +31
-1
lines changed Expand file tree Collapse file tree 1 file changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -28,7 +28,11 @@ Constraints:
28
28
29
29
*/
30
30
31
- /**
31
+
32
+
33
+ /**
34
+ * Initial solution using if statements
35
+ *
32
36
* @param {string } s
33
37
* @return {boolean }
34
38
*/
@@ -44,3 +48,29 @@ const isValid = (s) => {
44
48
45
49
return stack . length === 0 ;
46
50
} ;
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
+ } ;
You can’t perform that action at this time.
0 commit comments