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 ( is matched by a closing parenthesis ), and the pairs are properly nested.
Example 1
Input: (())()()
Output: 8
Explanation: The entire string is valid.
Example 2
Input: )((())
Output: 4
Explanation: The longest valid substring is (()).
Example 3
Input: (((())))()
Output: 10
Explanation: The entire string is valid.
Example 4
Input: ()(()
Output: 2
Explanation: The longest valid substring is ().
Constraints
Case 1
Input: '((())())'
Expected: 8
Case 2
Input: '(()))(()'
Expected: 4
Case 3
Input: '()()()()'
Expected: 8
Case 4
Input: '(((((('
Expected: 0
Case 5
Input: '())())())'
Expected: 2