-
Notifications
You must be signed in to change notification settings - Fork 8
/
balancedLongestContinousParenthesis.py
49 lines (46 loc) · 1.9 KB
/
balancedLongestContinousParenthesis.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
def longestBalancedParenthesisSubstring(string):
if len(string) == 0:
return 0
stack = []
maxlongestSubStrSoFar = 0
longestSubStrSoFar = 0
for ch in string:
if ch == "(":
stack.append(ch)
elif ch == ")":
if len(stack) != 0 and stack[-1] == "(":
_ = stack.pop()
longestSubStrSoFar += 2
if longestSubStrSoFar > maxlongestSubStrSoFar:
maxlongestSubStrSoFar = max(
longestSubStrSoFar, maxlongestSubStrSoFar)
else:
if longestSubStrSoFar > maxlongestSubStrSoFar:
maxlongestSubStrSoFar = max(
longestSubStrSoFar, maxlongestSubStrSoFar)
longestSubStrSoFar = 0
if len(stack) != 0:
stack = []
rmaxlongestSubStrSoFar = 0
longestSubStrSoFar = 0
for ch in string:
if ch == ")":
stack.append(ch)
elif ch == "(":
if len(stack) != 0 and stack[-1] == ")":
_ = stack.pop()
longestSubStrSoFar += 2
if longestSubStrSoFar > rmaxlongestSubStrSoFar:
maxlongestSubStrSoFar = max(
longestSubStrSoFar, rmaxlongestSubStrSoFar)
else:
if longestSubStrSoFar > rmaxlongestSubStrSoFar:
rmaxlongestSubStrSoFar = max(
longestSubStrSoFar, rmaxlongestSubStrSoFar)
longestSubStrSoFar = 0
return max(rmaxlongestSubStrSoFar, maxlongestSubStrSoFar)
return maxlongestSubStrSoFar
print(longestBalancedParenthesisSubstring("())(())"))
print(longestBalancedParenthesisSubstring(")(()))))((((()"))
print(longestBalancedParenthesisSubstring('()((())(())') == 4)
print(longestBalancedParenthesisSubstring('(()())'))