python版 最长回文字符串

# 给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 
# 
#  示例 1: 
# 
#  输入: "babad"
# 输出: "bab"
# 注意: "aba" 也是一个有效答案。
#  
# 
#  示例 2: 
# 
#  输入: "cbbd"
# 输出: "bb"
#  
#  Related Topics 字符串 动态规划 
#  👍 2959 👎 0


# leetcode submit region begin(Prohibit modification and deletion)
class Solution(object):

    def center(self, left, right, s):
        step = []
        if left == right:
            k = 1
            while left - k >= 0 and left + k < len(s):
                if s[left - k] == s[left + k]:
                    step = s[left - k: right + k + 1]

                    k += 1
                else:
                    break
        if left + 1 == right:
            k = 0
            while left - k >= 0 and right + k < len(s):
                if s[left - k] == s[right + k]:
                    step = s[left - k: right + k + 1]
                    k += 1
                else:
                    break

        return step

    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        l = []
        for i in range(0, len(s) - 1):
            step1 = self.center(i, i, s)
            step2 = self.center(i, i + 1, s)
            if len(l) < max(len(step1), len(step2)):
                if len(step1) > len(step2):
                    l = step1
                else:
                    l = step2
        if l == []:
            return s[0]
        return l
# s = "bbbbb"
# o = Solution()
# print(o.longestPalindrome(s))
# leetcode submit region end(Prohibit modification and deletion)

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页