'''
递推式:
1 一般: S[i+1] == S[j-1] and j>i and j-i == len(S[i+1,j-1])
2 初始化dp矩阵对角线的值为 true,相邻两个元素相等时dp[i][i+1] 为true ,初始化回文串起始位置和长度。
'''
def longestPalindrome(s):
n = len(s)
if s == '':
return ''
if n == 1:
return s
start = 0
max_len = 0
dp = [[False for i in range(n)] for j in range(n)]
for i in range(n):
dp[i][i] = True
if i + 1 < n:
#####如果两个连续字符相等,则i,i+1 为true
if s[i] == s[i + 1]:
dp[i][i + 1] = True
start = i
max_len = 2
if max_len == 0:
max_len = 1
start = 0
'''
前面的已经遍历到回文串长度为2,从长度为3开始,|i-j|=2开始
strlen [3,n+1]
'''
###dp[i][j]表示i到j是否是回文串,i < j 能保证不越界
for strlen in range(3, n + 1):
for i in range(n - strlen + 1):
j = i + strlen - 1
if s[i] == s[j] and dp[i + 1][j - 1]:
dp[i][j] = True
max_len = strlen
start = i
return s[start:start + max_len]
马拉车算法