File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
hard/0032 longest-valid-parentheses Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {string } s
3
+ * @return {number }
4
+ */
5
+ var longestValidParentheses = function ( s ) {
6
+ let maxLength = 0 ;
7
+ let stack = [ ] ;
8
+ stack . push ( - 1 ) ;
9
+ for ( let i = 0 ; i < s . length ; i ++ ) {
10
+ if ( s [ i ] == '(' ) {
11
+ stack . push ( i ) ;
12
+ } else {
13
+ stack . pop ( ) ;
14
+ if ( stack . length == 0 ) {
15
+ stack . push ( i )
16
+ } else {
17
+ maxLength = Math . max ( maxLength , i - stack [ stack . length - 1 ] )
18
+ }
19
+ }
20
+ }
21
+ return maxLength ;
22
+ } ;
23
+
24
+
25
+
26
+ console . log ( longestValidParentheses ( "(()" ) ) ;
27
+ console . log ( longestValidParentheses ( ")()())" ) ) ;
28
+ console . log ( longestValidParentheses ( ")(" ) ) ;
Original file line number Diff line number Diff line change
1
+ # Longest Valid Parentheses
2
+
3
+ Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
4
+
5
+ ## Example 1
6
+
7
+ Input: "(()"
8
+
9
+ Output: 2
10
+
11
+ Explanation: The longest valid parentheses substring is "()"
12
+
13
+ ## Example 2
14
+
15
+ Input: ")()())"
16
+
17
+ Output: 4
18
+
19
+ Explanation: The longest valid parentheses substring is "()()"
20
+
21
+ ## More info
22
+
23
+ < https://leetcode.com/problems/longest-valid-parentheses/ >
You can’t perform that action at this time.
0 commit comments