-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathLongest_Valid_Parentheses.py
More file actions
66 lines (59 loc) · 1.85 KB
/
Longest_Valid_Parentheses.py
File metadata and controls
66 lines (59 loc) · 1.85 KB
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
"""
@author Anirudh Sharma
Given a string containing just the characters '(' and ')', find the length of the
longest valid (well-formed) parentheses substring.
Constraints:
0 <= s.length <= 310^4
s[i] is '(', or ')'.
"""
def longestValidParentheses(s: str) -> int:
# Variable to store the longest valid parentheses
count = 0
# Left counter will count the number of '('
left = 0
# Right counter will count the number of ')'
right = 0
# Loop through the string from left to right.
# This will take care of extra right parentheses
for i in range(len(s)):
# Current character
c = s[i]
if c == '(':
left += 1
if c == ')':
right += 1
# If both left and right are equal,
# it means we have a valid substring
if left == right:
count = max(count, left + right)
# If right is greater than left,
# it means we need to set both
# counters to zero
if right > left:
left = right = 0
# Reset left and right
left = right = 0
# Follow the same approach but now loop the string
# from right to left. This will take care of extra
# left parentheses
for i in range(len(s) - 1, -1, -1):
# Current character
c = s[i]
if c == '(':
left += 1
if c == ')':
right += 1
# If both left and right are equal,
# it means we have a valid substring
if left == right:
count = max(count, left + right)
# If right is greater than left,
# it means we need to set both
# counters to zero
if left > right:
left = right = 0
return count
if __name__ == '__main__':
print(longestValidParentheses("(()"))
print(longestValidParentheses(")()()"))
print(longestValidParentheses(""))