File tree 2 files changed +37
-0
lines changed
2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change 37
37
29|[ Divide Two Integers] ( ./0029-divide-two-integers.js ) |Medium|
38
38
30|[ Substring with Concatenation of All Words] ( ./0030-substring-with-concatenation-of-all-words.js ) |Hard|
39
39
31|[ Next Permutation] ( ./0031-next-permutation.js ) |Medium|
40
+ 32|[ Longest Valid Parentheses] ( ./0032-longest-valid-parentheses.js ) |Hard|
40
41
33|[ Search in Rotated Sorted Array] ( ./0033-search-in-rotated-sorted-array.js ) |Medium|
41
42
34|[ Find First and Last Position of Element in Sorted Array] ( ./0034-find-first-and-last-position-of-element-in-sorted-array.js ) |Medium|
42
43
35|[ Search Insert Position] ( ./0035-search-insert-position.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 32. Longest Valid Parentheses
3
+ * https://leetcode.com/problems/longest-valid-parentheses/
4
+ * Difficulty: Hard
5
+ *
6
+ * Given a string containing just the characters '(' and ')', return the
7
+ * length of the longest valid (well-formed) parentheses substring.
8
+ */
9
+
10
+ /**
11
+ * @param {string } s
12
+ * @return {number }
13
+ */
14
+ var longestValidParentheses = function ( s ) {
15
+ if ( ! s . length ) {
16
+ return 0 ;
17
+ }
18
+
19
+ const stack = [ - 1 ] ;
20
+ let max = 0 ;
21
+
22
+ for ( let i = 0 ; i < s . length ; i ++ ) {
23
+ if ( s [ i ] === '(' ) {
24
+ stack . push ( i ) ;
25
+ } else {
26
+ stack . pop ( ) ;
27
+ if ( ! stack . length ) {
28
+ stack . push ( i ) ;
29
+ } else {
30
+ max = Math . max ( max , i - stack [ stack . length - 1 ] ) ;
31
+ }
32
+ }
33
+ }
34
+
35
+ return max ;
36
+ } ;
You can’t perform that action at this time.
0 commit comments