【代码随想录训练营】【Day 60】【动态规划-13】| Leetcode 647, 516
需强化知识点
- 动态规划-回文系列
题目
647. 回文子串
- 注意sum(dp)不行
- j的遍历要倒序,并且 for j in range(i, n):
python
class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
dp = [[0]*(n) for _ in range(n)]
result = 0
for i in range(n-1, -1, -1):
for j in range(i, n):
if s[i] == s[j]:
if j - i == 0:
dp[i][j] = 1
result += 1
elif abs(j - i) == 1:
dp[i][j] = 1
result += 1
else:
dp[i][j] = dp[i+1][j-1]
if dp[i+1][j-1]:
result += 1
else:
dp[i][j] = 0
return sum([sum(sublist) for sublist in dp])
516. 最长回文子序列
- 注意 python int max为 2**31 -1
- 滑动窗口,固定结束位置的方式,然后注意nums包含0,所以while判断是>=
python
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
# 以 i,j 的 最长序列长度
dp = [[0] * (n) for _ in range(n)]
for i in range(n):
dp[i][i] = 1
for i in range(n-1, -1, -1):
for j in range(i+1, n):
if s[i] == s[j]:
dp[i][j] = dp[i+1][j-1] + 2
else:
dp[i][j] = max(dp[i+1][j], dp[i][j-1])
return dp[0][n-1]