Python3最長回文子串算法示例
本文實例講述了Python3最長回文子串算法。分享給大家供大家參考,具體如下:
1. 暴力法
思路:對每一個子串判斷是否回文
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ if len(s) == 1: return s re = s[0] for i in range(0,len(s)-1): for j in range(i+1,len(s)): sta = i end = j flag = True while sta < end: if s[sta] != s[end]: flag = False break sta += 1 end -= 1 if flag and j-i+1 > len(re): re = s[i:j+1] return re
提交結(jié)果:超出時間限制
2. 動態(tài)規(guī)劃法
思路:
m[i][j]標記從第i個字符到第j個字符構(gòu)成的子串是否回文,若回文值為True,否則為False.
初始狀態(tài) s[i][i] == True,其余值為False.
當 s[i] == s[j] and m[i+1][j-1] == True 時,m[i][j] = True
class Solution: def longestPalindrome(self, s): """ :type s: str :rtype: str """ k = len(s) matrix = [[False for i in range(k)] for j in range(k)] re = s[0:1] for i in range(k): for j in range(k): if i==j: matrix[i][j] = True for t in range(1,len(s)): #分別考慮長度為2~len-1的子串(長串依賴短串的二維數(shù)組值) for i in range(k): j = i+t if j >= k: break if i+1 <= j-1 and matrix[i+1][j-1]==True and s[i] == s[j]: matrix[i][j] = True if t+1 > len(re): re = s[i:j+1] elif i+1 == j and j-1 == i and s[i] == s[j]: matrix[i][j] = True if t+1 > len(re): re = s[i:j+1] return re
執(zhí)行用時:8612 ms
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
詳解python 拆包可迭代數(shù)據(jù)如tuple, list
拆包是指將一個結(jié)構(gòu)中的數(shù)據(jù)拆分為多個單獨變量中。下面通過本文給大家介紹python 拆包可迭代數(shù)據(jù)如tuple, list的相關(guān)資料,需要的朋友參考下吧2017-12-12Python實現(xiàn)csv文件(點表和線表)轉(zhuǎn)換為shapefile文件的方法
這篇文章主要介紹了Python實現(xiàn)csv文件(點表和線表)轉(zhuǎn)換為shapefile文件的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-10-10Pygame游戲開發(fā)之太空射擊實戰(zhàn)敵人精靈篇
相信大多數(shù)8090后都玩過太空射擊游戲,在過去游戲不多的年代太空射擊自然屬于經(jīng)典好玩的一款了,今天我們來自己動手實現(xiàn)它,在編寫學習中回顧過往展望未來,下面開始講解敵人精靈的使用2022-08-08