5. 最长回文子串(中心展开法)

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

示例 1:

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

示例 2:

输入: "cbbd"
输出: "bb"

class Solution:
    def longestPalindrome(self, s):
        """
    :type s: str
    :rtype: str
    """
        slist = list(s)
        max = len(slist)
        max_list = slist[:1]

        def compare(left, right, max_list, slist):
            while left >= 0 and right < max:
                if slist[left] == slist[right]:
                    if len(max_list) <= len(slist[left:right + 1]):
                        max_list = slist[left:right + 1]
                else:
                    break
                left -= 1
                right += 1
            return max_list

        for i in range(max):
            left = i - 1
            right = i
            max_list = compare(left, right, max_list, slist)
            max_list = compare(left, right+1, max_list, slist)

        a = ''
        for i in max_list:
            a += i
        return a

 

你可能感兴趣的:(LeetCode,LeetCode,回文字符串)