好久不见。最近打算学习机器学习,开始练习用python编程。别的不说,没有大括号的语言看起来确实简洁优雅许多。
今晚做了一道最长回文子串的题目点击打开链接,需要在O(n)时间内完成。易见暴力的三次方,动态规划的平方和中心搜索的平方都不能满足要求。点击打开链接这里有着线性算法的详细解释,在此用python尝试将其转化,贴于下,与大家参考。
def solve(s):
'for finding the longest subpalindrome in s'
ss='^'
for char in s:
ss+='#'+char
ss+='#$'
l=len(ss)
p=[0]*(l+1)
c=r=0
for i in range(1,l-1):
mirrorI=2*c-i
if r>i:
p[i]=min(r-i,p[mirrorI])
while ss[i+1+p[i]]==ss[i-1-p[i]]:
p[i]+=1
if i+p[i]>r:
c=i
r=i+p[i]
maxLen=centerIndex=0
for i in range(1,l-1):
if p[i]>maxLen:
maxLen=p[i]
centerIndex=i
start=int((centerIndex-1-maxLen)/2)
print (s[start:start+maxLen])