索引i中的初始回文长度如何等于“Manacher算法”中的R - i?

问题描述 投票:0回答:1

我正在学习Manacher的算法来解决最长的Palindromic子串问题,我理解它利用了这样一个事实:如果我是回文的中心,那么将有一个以i为中心的回文。

我们维持一个数组P,而不是从0开始扩展,以便随时跟踪我的回文中心。我的问题是,如果镜子上的palindrom较小,我们怎么知道尺寸为R-i的回文?

这是它的代码。

    def longestPalindrome(self, s):
        # 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):

            if (R > i):
               # WHY R-i, how do we know there will be palindrome of size R -i
                P[i] =  min(R - i, P[2*C - i]) 

            # 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]

我发现的所有例子都是这样的

a # b # a # b # b # a # b # a
   i'          C         i    

据我所知,在这种情况下,我有一些subpalindromes,但是如果情况如此

a # b # c # d # d # c # b # a
   i'          C         i    

我们怎么知道P [i]在镜子里会是R-i还是Palindrome?

algorithm substring palindrome
1个回答
0
投票

这个页面解释了manacher的算法并用视觉动画回答了这个问题。

Visual explaination of Manacher's algorithm

© www.soinside.com 2019 - 2024. All rights reserved.