日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷(xiāo)解決方案
創(chuàng)新互聯(lián)Python教程:Python找回文子串的方法

1、雙指針兩邊擴(kuò)展

遍歷指針為i, j=i+1, i左移,j右移。判斷是否相等將長(zhǎng)度,下標(biāo)賦給臨時(shí)變量,最后切片返回。唯一的大坑?;匚淖址L(zhǎng)度可以是奇數(shù)也可以是偶數(shù)。奇數(shù)的時(shí)候,內(nèi)層循環(huán)從i-1開(kāi)始。邊界條件也需要處理好。

class Solution(object):
        
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        n = len(s)
        maxL, maxR, max = 0, 0, 0
        for i in range(n):
            # 長(zhǎng)度為偶數(shù)的回文字符串
            start = i
            end = i + 1
            while start >= 0 and end < n:
                if s[start] == s[end]:
                    if end - start + 1 > max:
                        max = end - start + 1
                        maxL = start
                        maxR = end
                    start -= 1
                    end += 1
                else:
                    break
    
            # 長(zhǎng)度為奇數(shù)的回文子串
            start = i - 1
            end = i + 1
            while start >= 0 and end < n:
                if s[start] == s[end]:
                    if end - start + 1 > max:
                        max = end - start + 1
                        maxL = start
                        maxR = end
                    start -= 1
                    end += 1
                else:
                    break
        return s[maxL:maxR+1]

2、Manacher算法

由于在輸入預(yù)處理的步驟中,將所有的回文子字符已經(jīng)轉(zhuǎn)為奇數(shù)長(zhǎng)度。所以在下面的操作中,只需要將輸入的每一個(gè)字符,都當(dāng)做一個(gè)回文子字符的中心位即可。不需要考慮偶數(shù)長(zhǎng)度的回文子字符。

'''
@author: Yizhou Zhao
'''
# 設(shè)置 radius[i] = 1, 因?yàn)樽址旧硪彩且粋€(gè)回文數(shù)
radius[i] = 1
while(string[i-radius[i]] == string[i+radius[i]]):
    radius[i] += 1

以上就是python找回文子串的方法,希望對(duì)大家有所幫助。更多Python學(xué)習(xí)指路:創(chuàng)新互聯(lián)Python教程

本文教程操作環(huán)境:windows7系統(tǒng)、Python 3.9.1,DELL G3電腦。


名稱(chēng)欄目:創(chuàng)新互聯(lián)Python教程:Python找回文子串的方法
文章出自:http://www.dlmjj.cn/article/cdpsehg.html