Problem
You receive a string brackets whose characters are all ( or ). Return the greatest length of a contiguous substring that forms a well-formed parentheses sequence.
A well-formed sequence pairs every opening parenthesis with a closing parenthesis in the correct nesting order. The characters you select must be adjacent in the original string; you cannot remove characters from the middle of a substring.
Return 0 if the string contains no nonempty well-formed substring, including when brackets is empty.
Examples
Example 1
Input: brackets = ")((()))()("
Output: 8
The substring ((()))() is well formed and contains eight characters. Neither character just outside it can extend it into a longer well-formed substring.
Example 2
Input: brackets = "((("
Output: 0
There are no closing parentheses, so no nonempty substring is well formed.
Constraints
-
0 <= brackets.length <= 3 * 10^4
-
Every character of
brackets
is
(
or
)
.