File tree 1 file changed +43
-0
lines changed
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ LeetCode -> https://leetcode.com/problems/longest-valid-parentheses/
3
+
4
+ Given a string containing just the characters '(' and ')',
5
+ find the length of the longest valid (well-formed) parentheses substring.
6
+ */
7
+
8
+ const longestValidParentheses = ( s ) => {
9
+ const n = s . length
10
+ const stack = [ ]
11
+
12
+ // storing results
13
+ const res = new Array ( n ) . fill ( - Infinity )
14
+
15
+ for ( let i = 0 ; i < n ; i ++ ) {
16
+ const bracket = s [ i ]
17
+
18
+ if ( bracket === ')' && s [ stack [ stack . length - 1 ] ] === '(' ) {
19
+ res [ i ] = 1
20
+ res [ stack [ stack . length - 1 ] ] = 1
21
+ stack . pop ( )
22
+ } else {
23
+ stack . push ( i )
24
+ }
25
+ }
26
+
27
+ // summing all adjacent valid
28
+ for ( let i = 1 ; i < n ; i ++ ) {
29
+ res [ i ] = Math . max ( res [ i ] , res [ i ] + res [ i - 1 ] )
30
+ }
31
+
32
+ // adding 0 if there are none so it will return 0 instead of -Infinity
33
+ res . push ( 0 )
34
+ return Math . max ( ...res )
35
+ }
36
+
37
+ const main = ( ) => {
38
+ console . log ( longestValidParentheses ( ')()())' ) ) // output -> 4
39
+ console . log ( longestValidParentheses ( '' ) ) // output -> 0
40
+ console . log ( longestValidParentheses ( '(()' ) ) // output -> 2
41
+ }
42
+
43
+ main ( )
You can’t perform that action at this time.
0 commit comments