# -*- coding:utf-8 -*- class Solution: def getLongestPalindrome(self, A, n): # write code here #根据题意最长回文子串长度至少为1,因此maxL初始化为1 maxL = 1 #从子串的中心向两端扩展,若两边元素一直相等,则继续扩展。此处,将扩展长度记为length1,则拓展方法可分为以下两种 #1、最长子串为奇数时,回文子串长度为2*length1-1,将其与当前最长长度相比即可。 for i in range(1,n-1): length1 = 1 while i-length1>=0 and i+length1<n: if A[i-length1] ==A[i+length1]: length1+=1 else: break maxL = max(maxL,2*length1-1) #最长子串为偶数时,回文子串长度为2*length2-2,将其与当前最长长度相比即可。 length2 = 1 while i-length2+1>=0 and i+length2<n: if A[i-length2+1] ==A[i+length2]: length2+=1 else: break maxL = max(maxL,2*length2-2) return maxL