-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathlongestBalancedSubstring.py
61 lines (58 loc) · 2.19 KB
/
longestBalancedSubstring.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
def longestBalancedSubstring(string):
stack = []
maxBalancedLengthSoFar = 0
numberOfOpeningParentheses = 0
currentLength = 0
store =[]
numberOfClosingParentheses = 0
for i in range(len(string)):
if string[i] == ')':
if len(stack) > 0:
top = stack[-1]
if top == "(":
numberOfClosingParentheses += 1
numberOfOpeningParentheses += 1
currentLength += 2
_ = stack.pop()
else:
currentLength = 0
numberOfClosingParentheses = 0
numberOfOpeningParentheses = 0
continue
elif string[i] == '(':
stack.append('(')
else:
pass
store.append(currentLength)
if currentLength > maxBalancedLengthSoFar and numberOfClosingParentheses == numberOfOpeningParentheses:
maxBalancedLengthSoFar = currentLength
stk=[]
maxBalancedLengthSoFar = 0
numberOfOpeningParentheses = 0
currentLength = 0
for i in reversed(range(len(string))):
if string[i] == ')':
if len(stack) > 0:
top = stack[-1]
if top == "(":
numberOfClosingParentheses += 1
numberOfOpeningParentheses += 1
currentLength += 2
_ = stack.pop()
else:
currentLength = 0
numberOfClosingParentheses = 0
numberOfOpeningParentheses = 0
continue
elif string[i] == ')':
stack.append(')')
else:
pass
if currentLength > maxBalancedLengthSoFar and numberOfClosingParentheses == numberOfOpeningParentheses:
maxBalancedLengthSoFar = currentLength
return maxBalancedLengthSoFar
print(longestBalancedSubstring("((()(())))))((()))(("))
print(longestBalancedSubstring("(()(()"))
print(longestBalancedSubstring("())))))())(((())((()"))
print(longestBalancedSubstring("())))))())(((())((()"))
print(longestBalancedSubstring("(()))("))