python;leetcode 最大回文数

直接暴力求解时间超出,选取Manacher算法

class Solution:

    
    def longestPalindrome(self, s):

        T = '$'+'#'+'#'.join(s)+'#'+'&' #前后插入$&是为了防止越界,不需要进行边界判断
        n = len(T)
        P = [0] * n  #每一处的回文半径
        C = R = 0    # R为当前访问到的最右边的值,C为此时对称轴的位置
        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)
            while T[i + 1 + P[i]] == T[i - 1 - P[i]]:
                P[i] += 1
            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]

你可能感兴趣的:(python;leetcode 最大回文数)