Given a string of parentheses (
and )
, find the length of the longest substring that forms a valid pair of parentheses.
Valid pairs of parentheses are defined as the following:
An empty string is a valid pair of parentheses.
If s
is a valid pair of parentheses, then (s)
is also a valid pair of parentheses.
If s
and t
are both valid pairs of parentheses, then st
is also a valid pair of parentheses.
For example, the longest valid substring of (()())
is (()())
, with length 6.
Write a function or program that takes a string of parentheses as input and outputs the length of the longest valid substring.
Example:
Input: (()())
Output: 6
Input: )()())
Output: 4
Input: ()(())
Output: 6
Input: ()(()
Output: 2
Input: ))
Output: 0
Input:
Output: 0
Code golf rules:
Write a function or program that takes a string of parentheses as input and outputs the length of the longest valid substring, using as few characters as possible.
The score of your solution will be the number of characters in your code. The solution with the shortest code wins. In case of ties, the earlier submission wins.
You can assume the input string contains only the characters (
and )
.
0
\$\endgroup\$0
, the expected answer is indeed the same as for an entirely invalid string. \$\endgroup\$0
, such asundefined
? \$\endgroup\$