Given a string containing just the characters '(' and ')', return the length of the longest valid (well-formed) parentheses substring. A parentheses substring is valid if every opening bracket has a matching closing bracket and the pairs are properly nested.
Example 1
Input: s = )()())
Output: 4
Explanation: The leading ')' can never be matched, but the next four characters "()()" form a well-formed run, so the longest valid substring has length 4.
Example 2
Input: s = (()
Output: 2
Explanation: Only the last two characters "()" pair up. The first '(' is left open, so the longest valid substring has length 2.
Example 3
Input: s = ()(())
Output: 6
Explanation: Every bracket is matched and properly nested, so the whole string of length 6 is valid.
Keep a stack of indices of characters that are so far unmatched, with a sentinel index just before any valid run begins. Every time a ')' closes something, the index now on top of the stack marks the boundary just before the current valid stretch, so the length of that stretch is simply the current index minus that boundary.
Run checks all cases above. Submit evaluates all test cases.