blob: c755993dbf8fe1382d59d8d8ffef40ec4a05258d (
plain)
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
|
#!/usr/bin/env python3
import re
import sys
def is_balanced(s: str) -> bool:
"""Check if a string of parentheses is balanced.
Args:
s (str): A string consisting of '(' and ')'.
Returns:
bool: True if the string is balanced, False otherwise.
"""
count = 0
for char in s:
if char == '(':
count += 1
elif char == ')':
if count == 0:
return False
count -= 1
return count == 0
def longest_parenthesis(input_string: str) -> int:
"""Return the length of the longest balanced parentheses substring.
Args:
input_string (str): A string consisting of '(' and ')'.
Returns:
int: Length of the longest balanced parentheses substring.
"""
# Check the input string is only parentheses
if not re.search(r'^[()]+$', input_string):
raise ValueError("Input string must contain only parentheses")
for length in range(len(input_string), 1, -1):
for start in range(len(input_string) - length + 1):
substring = input_string[start:start + length]
if is_balanced(substring):
return length
return 0
def main():
result = longest_parenthesis(sys.argv[1])
print(result)
if __name__ == '__main__':
main()
|