Skip to the content.

leetcode [5] 最长回文子串


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。

示例 2:

输入: "cbbd"
输出: "bb"
class Solution:
    def longestPalindrome(self, s: str) -> str:
        if len(s) < 2:
            return s
        
        ans, maxlen = None, 0
        for i in range(len(s)):
            # check odd
            left, right = i, i
            while left >= 0 and right < len(s) and s[left] == s[right]:
                if right - left + 1 > maxlen:
                    maxlen = right - left + 1
                    ans = s[left: right + 1]
                left, right = left - 1, right + 1
            # check even
            left, right = i, i + 1
            while left >= 0 and right < len(s) and s[left] == s[right]:
                if right - left + 1 > maxlen:
                    maxlen = right - left + 1
                    ans = s[left: right + 1]
                left, right = left - 1, right + 1

        return ans