Skip to content

Commit c33b21a

Browse files
Added solution
1 parent 6c8f448 commit c33b21a

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

longest_valid_parentheses.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution:
2+
def longestValidParentheses(self, s: str) -> int:
3+
if not s: return 0
4+
result, ind = 0, -1
5+
count, len_ = 0, 0
6+
for i in range(len(s)):
7+
len_ += 1
8+
if s[i] == '(':
9+
count += 1
10+
if s[i] == ')':
11+
count -= 1
12+
if count == 0 and len_ > result:
13+
result = len_
14+
if count < 0:
15+
len_, count = 0, 0
16+
17+
len_, count = 0, 0
18+
for i in range(len(s)-1, -1, -1):
19+
len_ += 1
20+
if s[i] == ')':
21+
count += 1
22+
if s[i] == '(':
23+
count -= 1
24+
if count == 0 and len_ > result:
25+
result = len_
26+
if count < 0:
27+
len_, count = 0, 0
28+
29+
return result

0 commit comments

Comments
 (0)