题解 | 最长回文子串

def longest_palindrome(s):
    def expand_around_center(left, right):
        # 从中心向左右扩展,找到最长的回文子串
        while left >= 0 and right < len(s) and s[left] == s[right]:
            left -= 1
            right += 1
        return s[left + 1:right]  # 返回当前找到的回文子串

    longest = ""
    for i in range(len(s)):
        # 奇数长度的回文子串
        odd = expand_around_center(i, i)
        # 偶数长度的回文子串
        even = expand_around_center(i, i + 1)
        # 更新最长的回文子串
        longest = max(longest, odd, even, key=len)
    return longest


s=input()

print(len(longest_palindrome(s)))

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务