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

应用更普遍的是动态规划解法:

核心思想:一个回文串去掉两头仍然是回文串

状态转移方程:如果  内部(去掉两头之后)是回文串 并且 两头处的元素相等,那么该串是回文串。 这样利用状态转移记录了之前的状态,减少了判断一个子串是否是回文串的时间,将时间复杂度由 O(n^3)降低为 O(n^2)

特殊情况:长度小于2,直接返回输入,无需判断















暴力匹配法

def longestPalindrome(self, s):
    """
    :type s: str
    :rtype: str
    """
    List , res_list = [] , []
    for i in range(len(s)):
        for j in range(len(s),i,-1):
            if s[i:j] == s[i:j][::-1]: # 这里的复杂度是O(n)
                List.append(j-i)
                res_list.append(s[i:j])
    if len(res_list) == 0:
        return ""
    else:
        m = List.index(max(List))

复杂度是 O(n^3)

中心扩散法:

def __center_spread(s, size, left, right):
        """
        left = right 的时候,此时回文中心是一条线,回文串的长度是奇数
        right = left + 1 的时候,此时回文中心是任意一个字符,回文串的长度是偶数
        """
        l = left
        r = right

        while l >= 0 and r < size and s[l] == s[r]:
            l -= 1
            r += 1
        return s[l + 1:r], r - l - 1

def longestPalindrome(s):
        size = len(s)
        if size == 0:
            return ''

        # 至少是 1
        longest_palindrome = 1
        longest_palindrome_str = s[0]

        for i in range(size):
            palindrome_odd, odd_len = __center_spread(s, size, i, i)
            palindrome_even, even_len = __center_spread(s, size, i, i + 1)

            # 当前找到的最长回文子串
            cur_max_sub = palindrome_odd if odd_len >= even_len else palindrome_even
            if len(cur_max_sub) > longest_palindrome:
                longest_palindrome = len(cur_max_sub)
                longest_palindrome_str = cur_max_sub

        return longest_palindrome_str

参考链接:

1: Manacher's ALGORITHM: O(n)时间求字符串的最长回文子串 - Felix021 - So far so good

2: LeetCode 5. Longest Palindromic Substring 最长回文子串 Python 四种解法(Manacher 动态规划)_小鹅鹅的博客-CSDN博客

3: hdu3068之manacher算法+详解_星天93的博客-CSDN博客_manacher算法

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

算法思想:

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值