本文實例講述了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
提交結果:超出時間限制
2. 動態規劃法
思路:
m[i][j]標記從第i個字符到第j個字符構成的子串是否回文,若回文值為True,否則為False.
初始狀態 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的子串(長串依賴短串的二維數組值) 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
執行用時:8612 ms
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答