def longestValidParentheses(s):
if not s:
return 0
res = 0
stack = [-1]
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
else:
stack.pop()
if not stack:
stack.append(i)
else:
res = max(res, i-stack[-1])
return res
# 方法二 动态规划
def longestValidParentheses(s):
n = len(s)
if n ==0:
return 0
dp = [0]*n
res = 0
for i in range(n):
if i>0 and s[i] == ")":
if s[i-1] == "(":
dp[i] = dp[i-2] + 2
elif s[i-1] == ")" and i-dp[i-1]-1>=0 and s[i-dp[i-1]-1] == "(":
dp[i] = dp[i-1]+2+dp[i-dp[i-1]-2]
if dp[i] > res:
res = dp[i]
return res
str = "()(()"
print(longestValidParentheses(str))
32_最长有效括号
最新推荐文章于 2024-03-23 13:42:20 发布