-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode#32.py
More file actions
33 lines (27 loc) · 828 Bytes
/
leetcode#32.py
File metadata and controls
33 lines (27 loc) · 828 Bytes
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
'''
# Time: O(n)
# Space: O(n)
#
# Given a string containing just the characters '(' and ')',
# find the length of the longest valid (well-formed) parentheses substring.
#
# For "(()", the longest valid parentheses substring is "()", which has length = 2.
#
# Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
#
'''
def longestValidParentheses(s):
longest, last, indices = 0, -1, []
for i in range(len(s)):
if s[i] == "(":
indices.append(i)
elif not indices:
last = i
else:
indices.pop()
if not indices:
longest = max(longest,i - last)
else:
longest = max(longest, i - indices[-1])
return longest
print(longestValidParentheses("(()"))