Skip to content

Longest Valid Parentheses

HardStack
Decode it first. Clues, constraints, pattern and plan before any code.

Given a string s of only ( and ), return the length of the longest contiguous substring that is a well-formed (balanced and properly nested) set of parentheses.

s = "(()"     →  2    ("()")
s = ")()())"  →  4    ("()()")
s = ""        →  0

Constraints

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