获取奇数回文长度 [英] Get Odd Length Palindrome

查看:62
本文介绍了获取奇数回文长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到最长的奇数回文,但是我编写的代码并没有给我完整的回文,只是其中的一部分.任何帮助都会很棒!

I'm trying to find the longest odd length palindrome, but the code I've written isn't giving me the full palindrome, just part of it. Any help would be great!

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

推荐答案

使iindex保持距离,并确保不要越界.最后,仅当找到i的最终值时,才构建结果字符串.每次迭代都没有用:

Make i the distance from the index and make sure not to loop out of bounds. Finally, only build the result string when you have found the final value of i. There is no use in doing it in every iteration:

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]

或者,您可以使用两个变量,从而稍微简化了代码:

Alternatively, you could use two variables, which simplifies the code a bit:

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]

这篇关于获取奇数回文长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆