32. Longest Valid Parentheses
class Solution:
def longestValidParentheses(self, s: str) -> int:
dp = [0] * len(s)
for i in range(0, len(s)):
if s[i] == "(":
continue
else:
if i - 1 >= 0:
p = i - dp[i - 1] - 1
# Try to find the first unmatched '('
if p >= 0 and s[p] == '(':
dp[i] += 2 + dp[i - 1]
if p - 1 >= 0:
dp[i] += dp[p - 1]
maxP = 0
for num in dp:
maxP = max(maxP, num)
return maxP