python动态规划求解最长回文子串

回文是什么,回文是正着读和反着读都是一样的字符叫着回文。
 如 ‘aba’,‘aa’,‘b’,这些都是回文
python动态规划求解最长回文子串_第1张图片

class Solution:
    def longestPalindrome(self,s: str) -> str:
        n = len(s)
        dp = [[False] * n for _ in range(n)]
        ans = ""
        for l in range(n):#l代表1个字符串,2个字符串,3个字符串  
            for i in range(n):
                j = i+l
                if j >= len(s):
                    break
                if l == 0:
                    dp[i][j] = True
                elif l ==1:
                    dp[i][j] = (s[i]==s[j])
                else:
                    dp[i][j] = (dp[i+1][j-1] and s[i]==s[j])
                if dp[i][j] and l+1>len(ans)
                    ans = s[i:j+1]
        return ans

你可能感兴趣的:(python,动态规划,开发语言)