题目描述:给你一个字符串 s
,找到 s
中最长的回文子串。如果字符串的反序与原始字符串相同,则该字符串称为回文字符串。
解题思路:
1.首先判断是否存在回文子串,不存在返回s[0]
2.回文子串长度有奇数,如:abcba,有偶数,如:abccba。
对于奇数子串可以从中间向两边扫描,当c的下标减去1与加1的字符相同时,表明存在回文串,并且可以继续向左右扫描。
对于偶数子串可以将第二个C与第一个C进行扫描,若相等则继续向左右扫描
class Solution:
def longestPalindrome(self, s: str) -> str:
max = 0 # 用于存储最大长度的回文串长度
res = '' # 存储回文串
str_len = 0 # 当前循环的回文串长度
# 奇数回文串aba,偶数回文串abccba
if len(s) == 1:
return s
for c in range(1, len(s)): # 从下标1开始,首先比对下标0与2或下标0
seek = 0
if_find = 0 # 用于检测是否存在回文串
# 奇数回文串abcba
while c-seek-1 >= 0 and c+seek+1 < len(s):
# 查找中心两边一一对应的字符
if s[c-seek-1] == s[c+seek+1]:
seek += 1
if_find = 1
else:
break # 不相同则跳出
if if_find != 0: # 找到了计算当前回文串长度
str_len = seek*2+1
elif max == 0: # 没找着并且最大回文串长度为0时给res赋值为s[0],避免输入一个字符的情况
res = s[0]
if str_len > max:
max = str_len
res = '' # 清空res再输入
for j in range(c-seek, c+seek+1):
res += s[j]
seek = 0
if_find = 0
# 偶数回文串abccba
while c-seek-1 >= 0 and c+seek < len(s):
if s[c-seek-1] == s[c+seek]: # 扫描当前位置和前一个位置的字符是否相同,是,则继续向左右依次扫描
seek += 1
if_find = 1
else:
break
if if_find != 0:
str_len = 2*seek
if str_len > max:
max = str_len
res = ''
for j in range(c-seek, c+seek):
res += s[j]
return res
s = Solution()
s1 = input()
res = s.longestPalindrome(s1)
print(res)