-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path32_longest_valid_parentheses.py
56 lines (47 loc) · 1.47 KB
/
32_longest_valid_parentheses.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
class Solution:
def longestValidParentheses0(self, s: str) -> int:
if not s:
return 0
dp = [0] * len(s)
for i in range(1, len(s)):
if s[i] == ')':
if s[i - 1] == '(':
dp[i] = (dp[i - 2] if i >= 2 else 0) + 2
elif i - dp[i - 1] > 0 and s[i - dp[i - 1] - 1] == '(':
dp[i] = dp[i - 1] + 2 + (0 if i - dp[i - 1] - 2 < 0 else dp[i - dp[i - 1] - 2])
return max(dp)
def longestValidParentheses(self, s: str) -> int:
left = right = max_length = 0
for c in s:
if c == '(':
left += 1
else:
right += 1
if left == right:
max_length = max(max_length, 2 * left)
elif right > left:
left = right = 0
left = right = 0
for i in range(len(s) - 1, -1, -1):
c = s[i]
if c == '(':
left += 1
else:
right += 1
if left == right:
max_length = max(max_length, 2 * left)
elif right < left:
left = right = 0
return max_length
def test():
sl = Solution()
for s, target in [
("()", 2),
("())", 2),
(")(())", 4),
(")()())", 4),
]:
ans = sl.longestValidParentheses(s)
assert ans == target, f"target: {target}, ans {ans}"
if __name__ == "__main__":
test()