Longest Valid Parentheses

HardStringStack

Description

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

Examples

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

In (( the valid substring is the last two chars () at indices 1-2, length 2.

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

In )()()) the substring ()() spans indices 1-4, giving maximum length 4.

Input:s = ""
Output:0
Explanation:

Empty string has no valid parentheses.

Constraints

  • 0 ≤ s.length ≤ 3 × 10⁴
  • s[i] is '(' or ')'.

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!