动态规划
class Solution:
def longestValidParentheses(self, s):
s = ' ' + s
size = len(s)
dp = [0] * size
for i in range(2, size):
if s[i] == ')':
if s[i - 1] == '(':
dp[i] = dp[i - 2] + 2
else:
if s[i - dp[i - 1] - 1] == '(':
dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2
return max(dp)
栈
class Solution:
def longestValidParentheses(self, s):
size = len(s)
rec = [False] * size
ll = []
for i in range(size):
if s[i] == '(':
ll.append(i)
else:
if ll:
j = ll.pop()
rec[i] = rec[j] = True
cnt = 0
maxl = 0
for i in rec:
if i:
cnt += 1
else:
maxl = max(maxl, cnt)
cnt = 0
maxl = max(maxl, cnt)
return maxl
标签:AC,python,32,ll,cnt,maxl,rec,dp,size
From: https://blog.csdn.net/qq_63443032/article/details/139205399