This commit is contained in:
nik
2025-10-01 22:55:09 +03:00
parent 4d0ece634b
commit 74e98c37c4
591 changed files with 20286 additions and 0 deletions

View File

@@ -0,0 +1 @@
https://leetcode.com/problems/longest-valid-parentheses/submissions/1769090768/?envType=problem-list-v2&envId=dynamic-programming

View File

@@ -0,0 +1,15 @@
class Solution:
def longestValidParentheses(self, s: str) -> int:
n = len(s)
dp = [0] * n
best = 0
for i in range(1, n):
if s[i] == ")":
if s[i - 1] == "(":
dp[i] = (dp[i - 2] if i >= 2 else 0) + 2
elif i - dp[i - 1] - 1 >= 0 and s[i - dp[i - 1] - 1] == "(":
dp[i] = dp[i - 1] + 2
if i - dp[i - 1] - 2 >= 0:
dp[i] += dp[i - dp[i - 1] - 2]
best = max(best, dp[i])
return best