回文子串
def countSubstrings(self, s):
count=0
dp=[[False]*len(s) for _ in range(len(s))]
for i in range(len(s)-1,-1,-1):
for j in range(i,len(s)):
if s[i]==s[j] :
if j-i<=1:
count+=1
dp[i][j]=True
elif dp[i+1][j-1]==True:
count+=1
dp[i][j]=True
return count
最长回文序列(不连续,可以删除某些元素形成回文)
def longestPalindromeSubseq(self, s):
"""
:type s: str
:rtype: int
"""
dp=[[0]*len(s) for _ in range(len(s))]
for i in range(len(s)):
dp[i][i]=1
for i in range(len(s)-1,-1,-1):
for j in range(i+1,len(s)):
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][len(s)-1]