Longest Valid Parentheses

Hard

Given a string containing only ( and ), return the length of the longest valid (well-formed) parentheses substring.

Example 1

longestValidParentheses()
Input
s = "(()"
Output
2

Why

The substring "()" is valid.

Example 2

longestValidParentheses()
Input
s = ")()())"
Output
4
Constraints
0 <= s.length <= 3 * 10^4
`s` contains only `(` and `)`.

Topics

StringsStackDynamic Programming

Implement longestValidParentheses in the editor and return the answer — printing it is never graded.