Skip to content
CodeShare
All problems

Longest Valid Parentheses

Find the longest well-formed run of parentheses.

HardStackDynamic programmingStrings

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

Examples

Example 1
Input
s = "(()"
Output
2
Why
The longest valid run is ().
Example 2
Input
s = ")()())"
Output
4
Why
The longest valid run is ()().
Example 3
Input
s = ""
Output
0

Constraints

  • 0 <= s.length <= 3 * 10^4
  • Each character is ( or ).