日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

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電腦。


網(wǎng)頁(yè)題目:創(chuàng)新互聯(lián)Python教程:Python找回文子串的方法
鏈接分享:http://m.5511xx.com/article/cdpsehg.html