-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest Valid Parentheses
55 lines (44 loc) · 1.27 KB
/
Longest Valid Parentheses
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
// Longest Valid Parentheses
# Time: O(n), Space: O(n)
class Solution:
def longestValidParentheses(self, s: str) -> int:
maxL = 0
stack = [-1]
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
stack.pop()
if stack == []:
stack.append(i)
else:
l = i - stack[-1]
maxL = max(maxL, l)
return maxL
# Time: O(n), Space: O(1)
class Solution:
def longestValidParentheses(self, s: str) -> int:
o, c = 0, 0
maxL = 0
for i in range(len(s)): # left to right
if s[i] == '(':
o += 1
else:
c += 1
if o == c:
l = o + c
maxL = max(maxL, l)
elif c > o:
o = c = 0
o, c = 0, 0
for i in range(len(s) - 1, -1, -1): # right to left
if s[i] == ')':
o += 1
else:
c += 1
if o == c:
l = o + c
maxL = max(maxL, l)
elif c > o:
o = c = 0
return maxL