题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
分两种情况:
1. abcba 形式
2. abba 形式
注意每种情况都要考虑下标最大不能超过字符串长度-1, 下标最小不能超过0.
s = input() l = [] for i in range(1, len(s)): p = s[i] q = '' n = 1 m = 0 while i-n>=0 and i+n<=len(s)-1 and s[i-n] == s[i+n]: p = s[i-n] + p + s[i+n] n += 1 if p != s[i]: l.append(p) while i-m>=0 and i+m+1<=len(s)-1 and s[i-m] == s[i+m+1]: q = s[i-m]+q+s[i+m+1] m += 1 if q: l.append(q) l.sort(key=lambda x: len(x)) print(len(l[-1]))