29. Longest Valid Parentheses
HardStrings~40 min
Given a string of only ( and ), return the length of the longest contiguous substring that is correctly matched.
A substring is correctly matched when every opening bracket has a matching closing bracket in the right order.
Examples
Example 1
- Input:
- str = "(()"
- Output:
- 2
- Why:
- The longest valid substring is "()".
Example 2
- Input:
- str = ")()())"
- Output:
- 4
- Why:
- The middle "()()" is valid.
Constraints
0 <= str.length <= 10000The string contains only ( and ).