最长回文子串

 

复制代码
remand = 'abaxyzzyxf'


def long_palindrome(s: str) -> str:
    longest = ''
    for i in range(len(s)):
        for j in range(i, len(s)):
            substr = s[i:j + 1]
            if is_palindrome(substr) and len(substr) > len(longest):
                longest = substr
    return longest


def is_palindrome(s: str) -> bool:
    # low = 0
    # high = len(s) - 1
    # while low <= high:
    #     if not s[low] == s[high]:
    #         return False
    #     low += 1
    #     high -= 1
    # return True
    return s == s[::-1]


print(long_palindrome(remand))
print(long_palindrome('abc'))
复制代码

 

复制代码
remand = 'abaxyzzyxf'


def long_palindrome(s: str) -> str:
    current = [0, 1]
    for idx in range(1, len(s)):
        odd = palindrome(s, idx - 1, idx + 1)
        even = palindrome(s, idx - 1, idx)
        long = max(odd, even, key=lambda item: item[1] - item[0])
        current = max(current, long, key=lambda item: item[1] - item[0])
    return s[current[0]: current[1]]


def palindrome(s: str, low: int, high: int) -> tuple[int, int]:
    length = len(s)
    while low >= 0 and high < length:
        if s[low] != s[high]:
            break
        low -= 1
        high += 1
    return low + 1, high


print(palindrome(remand, 0, 2))
print(long_palindrome(remand))
复制代码

 

posted @   ascertain  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2021-12-03 Ansible file module
2021-12-03 Allow non-root process to bind to port below 1024
点击右上角即可分享
微信分享提示