We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent c7143d6 commit f95aaf5Copy full SHA for f95aaf5
32-longest-valid-parentheses/longest-valid-parentheses.py
@@ -1,25 +1,19 @@
1
class Solution:
2
def longestValidParentheses(self, s: str) -> int:
3
- dp = [0] * len(s)
4
-
+ n = len(s)
+ dp = [0] * n
5
stack = []
6
7
- for i in range(len(s)):
8
- if not stack and s[i] == ")":
9
- continue
10
- elif s[i] == ")":
11
- dp[stack[len(stack) - 1]] = 1
12
- dp[i] = 1
13
- stack.pop()
14
- else:
+ for i, ch in enumerate(s):
+ if ch == '(':
15
stack.append(i)
+ elif stack:
+ open_idx = stack.pop()
+ dp[open_idx] = dp[i] = 1
16
17
- m = 0
18
- c = 0
19
20
- for i in range(len(dp)):
21
- c = c + 1 if dp[i] == 1 else 0
22
- m = max(m, c)
23
24
- return m
+ max_len = cur = 0
+ for val in dp:
+ cur = cur + 1 if val else 0
+ max_len = max(max_len, cur)
25
+ return max_len
0 commit comments