-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path032_longestParentheses.py
37 lines (29 loc) · 1.15 KB
/
032_longestParentheses.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
class Solution:
def longestValidParentheses(self, s: str) -> int:
temp_len = 0
max_len = 0
start = 0
stack = []
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
if stack == []:
start = i + 1
else:
stack.pop()
if stack == []:
temp_len = i - start + 1
max_len = max(temp_len, max_len)
else:
temp_len = i - stack[-1]
max_len = max(temp_len, max_len)
return max_len
print(Solution().longestValidParentheses(s = "()(")) #2
print(Solution().longestValidParentheses(s = "(())")) #4
print(Solution().longestValidParentheses(s = "()((())")) #4
print(Solution().longestValidParentheses(s = "(()")) #2
print(Solution().longestValidParentheses(s = ")()())")) #4
print(Solution().longestValidParentheses(s = "(())())"))
print(Solution().longestValidParentheses(s = "(()())"))
print(Solution().longestValidParentheses(s = ""))