File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ ## 32. Longest Valid Parentheses
2+
3+
4+ Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
5+
6+
7+ Example 1:
8+
9+ Input: s = "(()"
10+ Output: 2
11+ Explanation: The longest valid parentheses substring is "()".
12+ Example 2:
13+
14+ Input: s = ")()())"
15+ Output: 4
16+ Explanation: The longest valid parentheses substring is "()()".
17+ Example 3:
18+
19+ Input: s = ""
20+ Output: 0
21+
22+
23+ Constraints:
24+
25+ 0 <= s.length <= 3 * 104
26+ s[ i] is '(', or ')'.
27+
28+
29+ ``` python
30+ def longestValidParentheses (self , s : str ) -> int :
31+ if len (s) == 0 : return 0
32+ stack = [- 1 ]
33+ maxLen = 0
34+ for i in range (len (s)):
35+ if s[i] == ' (' :
36+ stack.append(i)
37+ else :
38+ stack.pop()
39+ if len (stack) == 0 :
40+ stack.append(i)
41+ else :
42+ maxLen = max (i- stack[- 1 ], maxLen)
43+ return maxLen
44+ ```
45+
46+ ```
47+ Runtime: 32 ms, faster than 99.13% of Python3 online submissions for Longest Valid Parentheses.
48+ Memory Usage: 14.4 MB, less than 5.50% of Python3 online submissions for Longest Valid Parentheses.
49+ ```
You can’t perform that action at this time.
0 commit comments