Menu
CoddyTech

Longest Valid Parentheses

You get a string s made only of the characters ( and ). Find the longest substring (a run of consecutive characters) that is well formed: every ( in it is closed by a later ) in it, and the pairs nest properly, as in (()()). Return the length of that substring, or 0 when not even () appears.

Function

longestValidParentheses(s: string) → integer
sstring
a string of ( and ) characters
Returnsinteger
the length of the longest well-formed substring, or 0 if there is none

Constraints

  • 1 ≤ s.length ≤ 6 × 104
  • Every character of s is ( or ).

Examples

Input
s = "()(())"
Output
6
Explanation
The whole string is well formed: () followed by (()). Two well-formed pieces side by side make one well-formed piece, so the answer is all 6 characters.

lock icon+21 hidden tests on Submit

challenge icon

Follow-up

Can you also report where the longest well-formed substring starts, choosing the leftmost one when several have the same length?

Reset code
def longestValidParentheses(s):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

s = "()(())"

Expected

6