Longest Valid Parentheses

Given a string s containing only '(' and ')', return the length of the longest valid (well-formed) parentheses substring. Example: Input: s = ")()())" Output: 4 Explanation: The longest valid substring is "()()" with length 4. Pattern focus: Monotonic Stack for matching indices.

Input Format

s = parentheses string

Output Format

length of the longest valid parentheses substring

Constraints

  • 0 <= s.length <= 10^5
  • s consists of '(' and ')'

Examples

Example 1:

Input:

s = "(()"

Output:

2

Explanation:

The substring '()' is the longest valid one.

Example 2:

Input:

s = ")()())"

Output:

4

Explanation:

The longest valid block is '()()'.

Loading...
Longest Valid Parentheses