美文网首页
5.Longest Palindromic Substring

5.Longest Palindromic Substring

作者: oneoverzero | 来源:发表于2020-01-27 14:40 被阅读0次

题目描述:

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

代码:(参考: https://leetcode.com/problems/longest-palindromic-substring/discuss/3337/Manacher-algorithm-in-Python-O(n)

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        # Transform S into T.
        # For example, S = "abba", T = "^#a#b#b#a#$".
        # ^ and $ signs are sentinels appended to each end to avoid bounds checking
        T = '#'.join('^{}$'.format(s))
        n = len(T)
        P = [0] * n
        C = R = 0
        for i in range (1, n-1):
            P[i] = (R > i) and min(R - i, P[2*C - i]) # equals to i' = C - (i-C)
            # Attempt to expand palindrome centered at i
            while T[i + 1 + P[i]] == T[i - 1 - P[i]]:
                P[i] += 1
    
            # If palindrome centered at i expand past R,
            # adjust center based on expanded palindrome.
            if i + P[i] > R:
                C, R = i, i + P[i]
    
        # Find the maximum element in P.
        maxLen, centerIndex = max((n, i) for i, n in enumerate(P))
        return s[(centerIndex  - maxLen)//2: (centerIndex  + maxLen)//2]

思路分析:

上述代码是 Manacher Algorithm (马拉车算法) 的 Python 实现。关于这一算法的介绍可以参考: https://www.jianshu.com/p/392172762e55

Manacher Algorithm 的时间复杂度和空间复杂度均为 O(n)

相关文章

网友评论

      本文标题:5.Longest Palindromic Substring

      本文链接:https://www.haomeiwen.com/subject/alhethtx.html