题解 | #密码截取#
密码截取
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
从头开始遍历,后面若有更长的对称段,必定随着遍历的进行,长度不断从旧的对称段长度开始增大
这样可以把时间压到50ms左右
def isSymmetric(s):
return s==s[::-1]
s=input()
maxL=1
# 以l和r标记对称段
l,r=0,1
for i in range(1,len(s)):
# 若第i个字符和对称段结尾相邻
if i==r:
# 若对称段向左右各扩展一位后对称
if l>0 and isSymmetric(s[l-1:i+1]):
l-=1
r+=1
# 若对称段向右扩展一位后对称
elif isSymmetric(s[l:i+1]):
r+=1
else:
pass
# 若第i个字符和对称段结尾不相邻
else:
count=0
# 从第i个字符往前maxL-1个字符开始往前搜索更长的对称段
for j in range(i+1-maxL,r-2,-1):
if isSymmetric(s[j:i+1]):
l=j
r=i+1
count=0
# 考虑到长度的奇偶性,对称段可能会隔一次迭代出现:d,vd,dvd
else:
count+=1
if count==2:
break
maxL=r-l
print(maxL)

