#32

Longest Valid Parentheses

master · 1750 · lc hard +32 · verified · 38.2% accepted · 13,266 likes · top 17%

play →

Description

Given a string of only '(' and ')', return the length of the longest contiguous substring that forms a valid, well-balanced parentheses sequence.

Example 1:

Input: s = "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()".

Example 2:

Input: s = ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()".

Example 3:

Input: s = ""
Output: 0

Code

1
2
3