参考:https://blog.csdn.net/asd136912/article/details/78987624
关键:
循环字符串一次,以回文长度为基础,试探当前长度,当前循环位置下,
(1)前后各加一是否构成回文,(2)或者往后加一是否构成回文。
之后返回起始位置及最长长度构成的字符串
class Solution:
def longestPalindrome(self,s):
str_length = len(s)
max_length = 0
start = 0
for i in range(str_length):
if i - max_length >= 1 and s[i - max_length - 1:i + 1] == s[i - max_length - 1:i + 1][::-1]:
start = i - max_length - 1
max_length += 2
continue
if i - max_length >= 0 and s[i - max_length:i + 1] == s[i - max_length:i + 1][::-1]:
start = i - max_length
max_length += 1
return s[start:start + max_length]
if __name__ =='__main__':
s='xabbac'
s1=Solution()
print(s1.longestPalindrome(s))