Python判断最长回文子字符串,怎么优化代码运行时间?
str1 = input()
# count,字符串数量
res_list = [] # res_list:存储匹配的回文字符串长度
for count in range(2, len(str1) + 1):
# 从回文字符串长度2开始遍历
j = 0 # j:控制起始索引和结束索引
while (count + j) <= len(str1): # 遍历所有count数量的子字符串
res_1 = str1[j : count + j] # 当前的子字符串
res_2 = res_1[::-1] # 倒置子字符串
if res_1 == res_2: # 回文字符串的判断:原字符串等于倒置后的字符串
res_list.append(count) # 如果满足条件,把回文字符串的数量添加到res_list列表
break
else:
j += 1 # 索引加1,切片往后移
print(max(res_list)) # 输出res_list中最大的数字