leetcode5:最长回文子串


给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

 

方法一:动态规划

对于一个子串而言,如果它是回文串,并且长度大于2,那么将它首尾的两个字母去除之后,它仍然是个回文串

用P(i, j)表示字符串s的第i到j个字母组成的串(s[i:j])是否为回文串

P(i, j) = P(i + 1, j - 1)^(Si == Sj)

P(i, i) = True

P(i, i + 1) = (Si == Si+1)

=================Python=============

O(n**2)  O(n**2)

class Solution:
    def longestPalindrome(self, s: str) -> str:
        dp = [[False] * len(s) for _ in range(len(s))]
        ans = ""
        #枚举子串的长度l + 1
        for l in range(len(s)):
            #枚举子串的起始位置i,这样可以通过j = i + 1得到子串的结束位置
            for i in range(len(s)):
                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

 

方法二:中心扩展算法  O(n**2)  O(1)

class Solution:
    def longestPalindrome(self, s: str) -> str:
        start, end = 0, 0
        for i in range(len(s)):
            left1, right1 = self.expandAroundCenter(s, i, i)
            left2, right2 = self.expandAroundCenter(s, i, i + 1)
            if right1 - left1 > end - start:
                start, end = left1, right1
            if right2 - left2 > end - start:
                start, end = left2, right2
        return s[start: end + 1]

    def expandAroundCenter(self, s, left, right):
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return left + 1, right - 1

 

方法三:Manacher算法

 

posted @ 2020-09-06 16:13  LinBupt  阅读(104)  评论(0编辑  收藏  举报