You are given a string s consisting only of the characters ( and ).
A string of parentheses is valid if every ( is closed by a matching ) later in the string and every pair is properly nested. For example, "(())()" is valid, but ")(" and "(()" are not.
Return the length of the longest substring of s that is a valid string of parentheses. If no substring of s is valid, return 0.
Examples
Example 1
Input: s = "(()"
Output: 2
Explanation: The longest valid substring is "()", which has length 2.
Example 2
Input: s = ")()())"
Output: 4
Explanation: The longest valid substring is "()()", which has length 4.
Example 3
Input: s = ""
Output: 0
Explanation: There is no substring to check, so the answer is 0.
Constraints
0≤n≤105 where n=s.length
s[i] is ( or )
Loading editor...
Run checks the sample cases; Submit runs every case.
Samples 3
Custom 0
passedwrong answertime limiterrorran, no expected valuenot run