Problems

Longest Valid Parentheses

hard
hard
strings
stack
dynamic-programming

Return the length of the longest contiguous substring of s that is a well-formed parentheses sequence.

Input / output

  • Input: s: string
  • Output: integer length

Examples

  1. "(()" returns 2.
  2. ")()())" returns 4 from "()()".

Constraints

  • 0 <= s.length <= 100,000
  • s contains only ( and )

Follow-up Compare stack, dynamic-programming, and two directional counter scans.

Examples

Example 1

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

Example 2

Input: s = ")()())"
Output: 4

Empty

Input: s = ""
Output: 0
🔒 5 hidden

Running will execute all 8 cases, including 5 hidden ones.