最长回文子串
给出字符串s,求s的最长的回文子串
法一 动态规划
用dp[i][j]表示从下标i到j的子串是否为回文串
初始化:dp[i][i]为True
- 用j从左往右遍历每个字符s[j]
- 对于某个j,用i从右往左遍历其左侧的每个字符s[i](保证i始终小于j)
- 状态转移方程:
若i==j
,dp[i][i]=True
若j-i==1
,dp[i][j]=(s[i]==s[j])
若j-i>1
, dp[i][j]=(s[i]==s[j]) and dp[i+1][j-1] - 若需要输出这个最长回文子串,则每次更新dp[i][j]时,若刷新了最长的记录,同步更新当前最长的回文子串长度maxLen=j-i+1和对应的起点i、终点j
- 复杂度O(n^2)
法二 马拉车算法
复杂度O(n)
def PreProcess(s:list):#预处理
r = "#".join(s)
r = list(r)
r.append("#")
r.insert(0,"#")
return r
def manacher(s:list):
mx = -1#回文串的右边界
id0 = -1#当前子串的中心
max_length = -1
centerIndex = -1
s = PreProcess(s)
p =[-1 for i in range(len(s))]
#print(s)
for i in range(1,len(s)-1):
if i < mx:
p[i] = min(mx-i,p[2*id0-i])
else:
p[i] = 1
while i >= p[i] and i+p[i]<len(p) and s[i-p[i]] == s[i+p[i]]:
p[i] += 1
if mx < i + p[i]:
mx = i + p[i]
id0 = i
if p[i]-1 > max_length:#找到更长的回文子串,记录其中心为centerIndex
centerIndex = i
max_length = p[i]-1
ans = s[centerIndex-p[centerIndex]+1:centerIndex+p[centerIndex]]
ans = "".join("".join(tmp).split("#"))
print(max_length)
print(ans)
return ans