新聞中心
這里有您想知道的互聯(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


咨詢
建站咨詢
