问题
解答
中心扩散法
算法
可以通过遍历字符串s
,寻找每个中心的所对应的最长回文子串。
注意:
如果最长回文子串长度是偶数,则中心为两个最中央字符串中间的间隙。
如果最长回文子串长度是偶数,则中心为一个中央字符。
时间复杂度
O(N^2)
class Solution:
def longestPalindrome(self, s: str) -> str:
Length = len(s)
if Length < 2:
return s
maxlen = 1
ans = s[0]
for i in range(Length):
temp1, temp1l = self.center_spread(s, Length, i, i)
temp2, temp2l = self.center_spread(s, Length, i, i + 1)
if temp1l >= maxlen:
tempmax = temp1
else:
tempmax = temp2
if len(tempmax) > maxlen:
maxlen = len(tempmax)
ans = tempmax
return ans
def center_spread(self, s, length, _left, _right):
left = _left
right = _right
while left >= 0 and right < length and s[left] == s[right]:
left -= 1
right += 1
return s[left + 1:right], right - left - 1
调试结果