/32. Longest Valid Parentheses

32. Longest Valid Parentheses

Hard
Strings38.2% acceptance

Given a string consisting only of the characters ( and ), determine the length of the longest contiguous substring that forms a valid sequence of parentheses. A valid sequence is one where every opening parenthesis ( is matched by a closing parenthesis ), and the pairs are properly nested.

Example 1

Input: (())()()

Output: 8

Explanation: The entire string is valid.

Example 2

Input: )((())

Output: 4

Explanation: The longest valid substring is (()).

Example 3

Input: (((())))()

Output: 10

Explanation: The entire string is valid.

Example 4

Input: ()(()

Output: 2

Explanation: The longest valid substring is ().

Constraints

  • 0 <= len(parenthesis_string) <= 30000
  • Each character in parenthesis_string is either ( or )
Python (current runtime)

Case 1

Input: '((())())'

Expected: 8

Case 2

Input: '(()))(()'

Expected: 4

Case 3

Input: '()()()()'

Expected: 8

Case 4

Input: '(((((('

Expected: 0

Case 5

Input: '())())())'

Expected: 2