题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
while True:
try:
s = input()
if len(s) ==1: #当输入s长度为1,直接返回1
print(1)
continue
res = 0 # res保存当前最长回文子串长度
for i in range(len(s)): # 分别用i,j两层循环遍历s的所有子串
for j in range(i+1, len(s)+1): # 注意j变量在range中要从i+1到len(s)+1
if s[i:j] == s[i:j][::-1]: # 判断是否回文
if len(s[i:j]) >= res and len(s[i:j])>=2: # 注意s长度大于等于2时,如果是回文子串,那么最小的res值是2。这里第二个条件是一个判断保护,避免将非回文的abcd第一个字符将res刷新为1。
res = len(s[i:j]) # res刷新为当前回文子串长度
print(res) # 打印结果
except:
break
