#动态规划,主要利用如果i+1到j-1是回文字符串且s[i]==s[j]那么i 到 j也是回文字符串
1 class Solution: 2 def longestPalindrome(self, s): 3 """ 4 :type s: str 5 :rtype: str 6 """ 7 n=len(s) 8 aa=[0]*(n*n) 9 longest='' 10 for i in range(n): 11 aa[i*n+i]=1 #单个字符肯定是回文字符串,用于回文长度为3的判断 12 longest=s[i] 13 for i in range(n-1): 14 if s[i]==s[i+1]: 15 aa[i*n+i+1]=1 #如果两个字符相同,那么它们也构成回文字符串,用于回文长度为4的判断 16 longest=s[i:i+2] 17 for l in range(3,n+1): 18 for i in range(0,n-l+1): 19 e=l+i-1 20 if (aa[(i+1)*n+e-1] & int(s[i]==s[e])): 21 longest=s[i:e+1] 22 aa[i*n+e]=1 23 return longest 24