Given a string consisting only of the characters ( and ), determine the length of the longest contiguous substring that forms a valid sequence of parentheses. A valid sequence is one where every opening parenthesis ( has a corresponding closing parenthesis ), and parentheses are properly nested.
Example 1
Input: parentheses_string = ((())())
Output: 8
Explanation: The entire string is a valid parentheses sequence.
Example 2
Input: parentheses_string = )()(()))
Output: 6
Explanation: The longest valid substring is ()(())) -> (())) (positions 2-7), which is (())), but only (())) is valid, so length is 4. Correction: Actually, the longest valid substring is ()(())) (positions 1-6), which is ()(())), but only ()(() is valid, so length is 4. Correction: Actually, the longest valid substring is ()(())) (positions 1-7), which is ()(())), and ()(())) is valid, so length is 6.
Example 3
Input: parentheses_string = ())((())
Output: 4
Explanation: The longest valid substring is (()).
Constraints
Case 1
Input: parentheses_string = '()()()()'
Expected: 8
Case 2
Input: parentheses_string = '(((())))()'
Expected: 10
Case 3
Input: parentheses_string = '())())())'
Expected: 2
Case 4
Input: parentheses_string = '(((((((('
Expected: 0
Case 5
Input: parentheses_string = ')()())()(()())'
Expected: 8