0
点赞
收藏
分享

微信扫一扫

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


回文是什么,回文是正着读和反着读都是一样的字符叫着回文。

 如 ‘aba’,‘aa’,‘b’,这些都是回文

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

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


举报

相关推荐

0 条评论