我试图找到最长的奇数长度回文,但我编写的代码没有给我完整的回文,只是其中的一部分。任何帮助都会很棒!
def get_odd_palindrome_at(s, index):
''' (str, int) -> str
> get_odd_palindrome_at('tbababt', 3)
'tbababt'
> get_odd_palindrome_at('color', 2)
'olo'
'''
palindrome = s[index]
i = index
for char in s:
if s[i - 1] == s[i + 1]:
palindrome = s[i - 1] + palindrome + s[i + 1]
i = i + 1
return palindrome
Make i
距离index
并确保不要循环出界。最后,只有在找到最终值时才构建结果字符串i
。在每次迭代中都这样做是没有用的:
def get_odd_palindrome_at(s, index):
for i in range(1, index+1):
if index + i >= len(s) or s[index - i] != s[index + i]:
i -= 1
break
return s[index-i:index+i+1]
或者,您可以使用两个变量,这会稍微简化代码:
def get_odd_palindrome_at(s, index):
i = index
j = index
while i >= 0 and j < len(s) and s[i] == s[j]:
i -= 1
j += 1
return s[i+1:j]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)