马拉车manacher算法-最长回文子串(python)

参考链接:

1: https://www.felix021.com/blog/read.php?2040

2: https://blog.csdn.net/asd136912/article/details/78987624

3: https://blog.csdn.net/xingyeyongheng/article/details/9310555

【最好录个视频,便于把这个算法讲清楚】

算法思想:

1,在字符串的两两字符之间和首位,都添加额外的符号(如“#”),把奇/偶长度的字符串S都变成奇数长度的字符串T

2,T具有以下性质:T中p[i]-1就是原S中回文字符串的长度

i:当前考虑的中心位置

p[i]:以i为中心的回文子串半径

id:之前处理的最长回文子串中心

mx:之前处理的最长回文子串右边界

j:i关于id的对称位置

p[j]:以j为中心的回文子串半径

3,求解p[i],分情况讨论(详见参考链接1):

1) mx > i,继续分两种情况

1.1) 若p[j] >= mx-i,则p[i] >= mx-i

1.2) 若p[j]  < mx-i,则p[i] = p[j]

综上,p[i] >= min(p[j], mx-i) , 赋值p[i] = min(p[j], mx-i) ,然后p[i] 从  min(p[j], mx-i) 开始逐渐左右延展,开始向外匹配

2) mx <= i:

则p[i] >= 1, 赋值 p[i] = 1,然后p[i] 从  1 开始逐渐左右延展,开始向外匹配

 

python代码:

返回最长回文子串长度和最长回文子串本身。

def manacher(self):
        s = '#' + '#'.join(self) + '#' # 字符串处理,用特殊字符隔离字符串,方便处理偶数子串
        lens = len(s)
        p = [0] * lens            # p[i]表示i作中心的最长回文子串的半径,初始化p[i]
        mx = 0                    # 之前最长回文子串的右边界
        id = 0                    # 之前最长回文子串的中心位置
        for i in range(lens):     # 遍历字符串
            if mx > i:
                p[i] = min(mx-i, p[int(2*id-i)]) #由理论分析得到
            else :                # mx <= i
                p[i] = 1
            while i-p[i] >= 0 and i+p[i] < lens and s[i-p[i]] == s[i+p[i]]:  # 满足回文条件的情况下
                p[i] += 1  # 两边扩展
            if(i+p[i]) > mx:  # 新子串右边界超过了之前最长子串右边界
                mx, id = i+p[i], i # 移动之前最长回文子串的中心位置和边界,继续向右匹配
        i_res = p.index(max(p)) # 获取最终最长子串中心位置
        s_res = s[i_res-(p[i_res]-1):i_res+p[i_res]] #获取最终最长子串,带"#"
        return s_res.replace('#', ''), max(p)-1  #返回最长回文子串(去掉"#")和它的长度

print(manacher(''))
print(manacher(' '))
print(manacher('babad'))
print(manacher('cbbd'))
print(manacher('nw'))
print(manacher('bbbb'))
print(manacher('civilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth'))




输出:

('', 0)
(' ', 1)
('bab', 3)
('bb', 2)
('n', 1)
('bbbb', 4)
('ranynar', 7)

Process finished with exit code 0

你可能感兴趣的:(leetcode)