目录
647. 回文子串
class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
#dp[i][j]:s的i到j子串是否为回文子串
dp = [[False]*(n) for _ in range(n)]
res = 0
for i in range(n-1,-1,-1):
for j in range(i,n):
if s[i] == s[j]:
if j-i <= 1:
res += 1
dp[i][j] = True
elif dp[i+1][j-1]:
res += 1
dp[i][j] = True
return res
516.最长回文子序列
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
#dp[i][j]: 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][-1]