美文网首页
5.最长回文子串

5.最长回文子串

作者: 御坂10241 | 来源:发表于2020-05-05 16:43 被阅读0次
chaoxi_todo.jpg

题目

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

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

示例 2:
输入: "cbbd"
输出: "bb"

题解

def longestPalindrome(self, s: str) -> str:
        res = ""  # 存储找到的最长的回文字符串
        for i in range(len(s)):
            start = max(0, i-len(res)-1)
            temp = s[start: i+1]
            if temp == temp[::-1]:  # 判断是否是比res多两位的回文
                """例如:abcdcba"""
                res = temp
            else:
                temp = temp[1:]
                if temp == temp[::-1]:  # 判断是否是比res多一位的回文
                    """"""例如:abcddcba""""""
                    res = temp
        return res

执行结果:通过
显示详情
执行用时 :68 ms, 在所有 Python3 提交中击败了98.80%的用户
内存消耗 :13.7 MB, 在所有 Python3 提交中击败了9.26%的用户

相关文章

网友评论

      本文标题:5.最长回文子串

      本文链接:https://www.haomeiwen.com/subject/cjudghtx.html