Longest Valid Parentheses

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

A valid parentheses substring is a contiguous substring where every opening parenthesis '(' is matched with a later closing parenthesis ')' in the correct order.

Example 1
Inputs = "(()"
Output2
The longest valid parentheses substring is "()", which has length 2.
Example 2
Inputs = ")()())"
Output4
The longest valid parentheses substring is "()()", which has length 4.

Constraints

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

Asked at 28 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate