目录
学习目标
- 647. 回文子串
- 516.最长回文子序列
- 动态规划总结篇
学习内容
647. 回文子串
647. 回文子串 - 力扣(LeetCode)https://leetcode.cn/problems/palindromic-substrings/
class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
dp = [[0]*(n+1)for _ in range(n+1)]
res = n
for i in range(n,0,-1):
for j in range(n+1):
if i>=j:
dp[i][j]=1
elif s[i-1]==s[j-1] and dp[i+1][j-1]:
dp[i][j]=1
res+=1
#print(dp)
return res
class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
res = 0
for i in range(n):
left = i-1
right = i+1
tmp = 1
while left>-1 and right<n and s[left]==s[right]:
tmp+=1
left-=1
right+=1
res+=tmp
for i in range(n-1):
j=i+1
left = i
right = j
tmp = 0
while left>-1 and right<n and s[left]==s[right]:
tmp+=1
left-=1
right+=1
res+=tmp
return res
516.最长回文子序列
516. 最长回文子序列 - 力扣(LeetCode)https://leetcode.cn/problems/longest-palindromic-subsequence/
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
dp = [[0]*(n+1)for _ in range(n+1)]
for i in range(n,0,-1):
for j in range(n+1):
if i>j:continue
elif i==j:dp[i][j]=1
elif s[i-1]==s[j-1]:
dp[i][j]=dp[i+1][j-1]+2
else:
dp[i][j]=max(dp[i+1][j],dp[i][j-1])
#print(dp)
return dp[1][n]
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
dp = [0]*(n+1)
for i in range(n,0,-1):
tmp = [0]*(n+1)
for j in range(n+1):
if i>j:continue
elif i==j:tmp[j]=1
elif s[i-1]==s[j-1]:
tmp[j]=dp[j-1]+2
else:
tmp[j]=max(dp[j],tmp[j-1])
dp = tmp
#print(dp)
return dp[n]