题解 | 最长回文子串
最长回文子串
https://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param A string字符串
# @return int整型
#
class Solution:
def getLongestPalindrome(self , A: str) -> int:
n = len(A)
max_len = 1
def expand(left, right):
""" 从中心向两侧扩展,返回最长回文子串的长度"""
while left >= 0 and right < n and A[left] == A[right]:
left -= 1
right += 1
# 退出循环时,有效回文长度为(right-1) - (left+1) + 1
return right - left - 1
for i in range(n):
# 以单个字符为中心(奇数长度回文)
len_odd = expand(i,i)
# 以两个字符为中心(偶数长度回文)
len_even = expand(i,i+1)
current_max = max(len_odd,len_even)
if current_max > max_len:
max_len = current_max
return max_len
python版本
查看19道真题和解析
