Longest Properly Closed Bracket Run
Problem statement
A string of brackets is valid when every ( is closed by a later ) and every ) closes an earlier (, like (()()).
Given a string s of ( and ), return the length of its longest contiguous substring that is valid (0 if there is none).
Function
longestValid(s: String) → intExamples
Example 1
s = "())(())"return = 4The first two characters () are valid, but the third character ) has no partner and breaks the run. After it, (()) is valid and has length 4.
Example 2
s = "(((("return = 0No ( is ever closed, so there is no valid stretch: 0.
Example 3
s = "()(()"return = 2() has length 2. The rest, ((), contains the valid () at the end, also length 2, but the unclosed ( in the middle stops the two from joining. The answer is 2.
Constraints
0 <= s.length <= 3000scontains only the characters'('and')'