File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * https://leetcode.com/problems/valid-parentheses/
3
+ *
4
+ * stack Data structure example
5
+ * https://initjs.org/data-structure-stack-in-javascript-714f45dbf889
6
+ *
7
+ */
8
+
9
+ /**
10
+ * @param {string } s
11
+ * @return {boolean }
12
+ */
13
+ var isValid = function ( s ) {
14
+ if ( s . length == 1 ) return false
15
+ if ( s . length == 0 ) return true
16
+
17
+ let stack = [ ]
18
+ let myMap = new Map ( )
19
+ myMap . set ( '(' , ')' )
20
+ myMap . set ( '{' , '}' )
21
+ myMap . set ( '[' , ']' )
22
+
23
+ for ( char of s ) { // complexity in O(N) as we go throught the string once
24
+ if ( char === '(' || char === '{' || char === '[' ) {
25
+ stack . push ( char ) // in worst case it gives another O(N) in space and time "((((((..."
26
+ } else {
27
+ if ( char !== myMap . get ( stack [ stack . length - 1 ] ) )
28
+ return false
29
+ stack . pop ( )
30
+ }
31
+ }
32
+
33
+ return stack . length === 0
34
+ } ;
You can’t perform that action at this time.
0 commit comments