Skip to content

Commit b9c7a17

Browse files
authored
Create longest_valid_paranthesis.py
made necessary changes!
1 parent 51dba4d commit b9c7a17

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

strings/longest_valid_paranthesis.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
def longest_valid_paranthesis(self, s: str) -> int:
2+
"""
3+
Returns the length of the longest valid paranthesis
4+
>>> longest_valid_paranthesis('(()')
5+
2
6+
>>> longest_valid_paranthesis(')()())')
7+
4
8+
>>> longest_valid_paranthesis('')
9+
0
10+
>>> longest_valid_paranthesis(''(())))((()(()()()())
11+
8
12+
"""
13+
stack = []
14+
preceeding_matched = 0
15+
res = 0
16+
for char in s:
17+
if char == "(":
18+
stack.append(preceeding_matched)
19+
preceeding_matched = 0
20+
else:
21+
if stack:
22+
preceeding_matched += 1 + stack.pop()
23+
else:
24+
res = max(res, preceeding_matched)
25+
preceeding_matched = 0
26+
27+
res = max(res, preceeding_matched)
28+
29+
while stack:
30+
res = max(res, stack.pop())
31+
32+
return res * 2

0 commit comments

Comments
 (0)