https://leetcode.com/problems/longest-valid-parentheses/
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
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
Constraints:
0 <= s.length <= 3 * 104
s[i] is '(', or ')'.
- code
class Solution:
def longestValidParentheses(self, s: str) -> int:
l = r = 0
res = 0
for v in s:
if v == "(":
l += 1
else:
r += 1
if l == r:
res = max(res, 2 * r)
if r > l:
l = r = 0
l = r = 0
for i in reversed(range(len(s))):
if s[i] == "(":
l += 1
else:
r += 1
if l == r:
res = max(res, 2 * r)
if l > r:
l = r = 0
return res