题解 | #最长回文子串#
最长回文子串
http://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
颇为繁琐的解法
从左到右依次遍历,先判断当前元素是不是字长为偶数回文字符串的中心,如果是,依次向两边扩展并判断,直至不满足回文字符串要求为止;再判断,当前元素是不是字长为奇数的偶数回文子串的中心,同理;看了题解之后,发现这种做法实在过于低级,直接判断这个子串的正序输出和逆序是否相等即可
L = []
while True:
try:
L.append(input())
except:
break
for m in range(len(L)):
if len(L[m]) == 1:
print(1)
else:
max1 = 1
for i in range(1, len(L[m])):
k = 0 # 记录对称点向两边位移的个数
if i-k >= 0 and i+1+k < len(L[m]):
while L[m][i-k] == L[m][i+1+k] and i-k >= 0 and i+1+k < len(L[m]):
k += 1
if i-k < 0 or i+1+k >= len(L[m]):
break
if max1 < 2k:
max1 = 2*k
k = 1
if i-k >= 0 and i+k < len(L[m]):
while L[m][i-k] == L[m][i+k] and i-k >= 0 and i+k < len(L[m]):
k += 1
if i-k < 0 or i+k >= len(L[m]):
break
if max1 < 2(k-1) + 1:
max1 = 2*(k-1) + 1
print(max1)