2021-12-23 5. 最长回文子串【Medium】

给你一个字符串 s,找到 s 中最长的回文子串。

示例 1:

输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。

示例 2:

输入:s = "cbbd"
输出:"bb"

示例 3:

输入:s = "a"
输出:"a"

示例 4:

输入:s = "ac"
输出:"a"

提示:

1 <= s.length <= 1000
s 仅由数字和英文字母(大写和/或小写)组成

方法一:

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n = len(s)
        def getLen(l, r):
            while l >= 0 and r < n and s[l] == s[r]:
                l -= 1
                r += 1
            return r - l - 1

        start = 0
        length = 0
        for i in range(n):
            cur = max(getLen(i, i), getLen(i, i + 1))
            if cur <= length: continue
            length = cur
            start = i - (cur - 1) // 2

        return s[start : start + length]

你可能感兴趣的:(2021-12-23 5. 最长回文子串【Medium】)