Skip to content

Commit 1c90ee1

Browse files
authored
Create 32_Longest_Valid_Parentheses.md
1 parent d15270b commit 1c90ee1

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

32_Longest_Valid_Parentheses.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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+
```

0 commit comments

Comments
 (0)