先将代码给出来,以后补充代码的解释,另外说明一下,函数输出的是回文子串的最大长度以及具有最大长度的所有回文子串的数组(具有最大长度的回文子串可能不止一个)
def my_function(s):
Str=''
for i in range(len(s)):
Str=Str+' '+s[i]
Str=Str+' ' #在字符串中间加入特殊字符‘ ’,保证新的字符串的回文子串中心为一个字符,且不会改变回文子串
cover=0
cover_center=0
center=[(Str[0],0)]
length=0
length_max=1
length_max_=[]
for i in range(1,len(Str)):
if cover != len(Str)-1:
if i<cover:
if center[2*cover_center-i][1]<cover-i:
center.append((Str[i],center[2*cover_center-i][1]))
else:
length=cover-i
for j in range(cover-i,min(i,len(Str)-i-1)):
if Str[i-j-1] == Str[i+j+1]:
length+=1
else:
break
center.append((Str[i],length))
cover=i+length
cover_center=i
if length>length_max:
length_max_=[]
if length>=length_max:
length_max_.append(i)
length_max=length
length=0
else:
for j in range(min(i,len(Str)-i-1)):
if Str[i-j-1] == Str[i+j+1]:
length+=1
else:
break
center.append((Str[i],length))
cover=i+length
cover_center=i
if length>length_max:
length_max_=[]
if length>=length_max:
length_max_.append(i)
length_max=length
length=0
S=[]
if length_max%2 == 0:
for i in length_max_:
S.append(s[i//2-length_max//2:i//2+length_max//2])
else:
for i in length_max_:
S.append(s[i//2-length_max//2:i//2+length_max//2+1])
return length_max,S
if __name__=='__main__':
length_max,S=my_function('abc')
print('length_max:',length_max)
for i in S:
print(i)
运行结果
length_max: 1
a
b
c