-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy pathlongest-balanced-substring.py
93 lines (77 loc) · 2.01 KB
/
longest-balanced-substring.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# LONGEST BALANCED SUBSTRING
# O(n) time and space
def longestBalancedSubstring(string):
# Write your code here.
maxLength = 0
idxStack = []
idxStack.append(-1)
for i in range(len(string)):
if string[i] == "(":
idxStack.append(i)
else:
idxStack.pop()
if len(idxStack) == 0:
idxStack.append(i)
else:
balancedSubstringStartIdx = idxStack[len(idxStack) - 1]
currentLength = i - balancedSubstringStartIdx
maxLength = max(maxLength, currentLength)
return maxLength
# O(N) time and O(1) space
def longestBalancedSubstring(string):
# Write your code here.
maxLength = 0
openingCount = 0
closingCount = 0
for char in string:
if char == "(":
openingCount += 1
else:
closingCount += 1
if openingCount == closingCount:
maxLength = max(maxLength, closingCount * 2)
elif closingCount > openingCount:
openingCount = 0
closingCount = 0
openingCount = 0
closingCount = 0
for i in reversed(range(len(string))):
char = string[i]
if char == "(":
openingCount += 1
else:
closingCount += 1
if openingCount == closingCount:
maxLength = max(maxLength, openingCount * 2)
elif openingCount > closingCount:
openingCount = 0
closingCount = 0
return maxLength
# O(N) time and O(1) space
def longestBalancedSubstring(string):
# Write your code here.
return max(
getLongestBalancedInDirection(string, True),
getLongestBalancedInDirection(string, False),
)
def getLongestBalancedInDirection(string, leftToRight):
openingParens = "(" if leftToRight else ")"
startIdx = 0 if leftToRight else len(string) - 1
step = 1 if leftToRight else -1
maxLength = 0
openingCount = 0
closingCount = 0
idx = startIdx
while idx >= 0 and idx < len(string):
char = string[idx]
if char == openingParens:
openingCount += 1
else:
closingCount += 1
if openingCount == closingCount:
maxLength = max(maxLength, closingCount * 2)
elif closingCount > openingCount:
openingCount = 0
closingCount = 0
idx += step
return maxLength