33. Longest Valid Parentheses
Hard · String
Given a string containing only characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
A valid parentheses string is one where every opening bracket has a matching closing bracket in the correct order. For example, "()" and "(())" are valid, but ")()())" is not entirely valid (though it contains "()" as a valid substring).
Return the length of the longest contiguous substring that forms valid parentheses.
Examples
Example 1 Input: "(()" Output: 2 Explanation: The longest valid parentheses substring is "()" with length 2.
Example 2 Input: ")()())" Output: 4 Explanation: The longest valid parentheses substring is "()()" with length 4.
Constraints
- Standard input/output constraints apply