菜鸟leetcode生涯(三):最长回文子串

题目描述

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

思路

我采用的是最笨的方法:要找最长回文子串,就从最长字符开始,如果不符合回文子串,则字符长度减一后继续判断,直到字符长度为0为止。

代码段(python3)

class Solution:
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        l = len(s)
        c = 0
        while l != 0:
            for i in range(c+1):
                a1 = s[i:i+l]
                a2 = a1[::-1]
                if a1 == a2:
                    return a1
            l -= 1 
            c += 1
        if l ==0:
            return ''

猜你喜欢

转载自blog.csdn.net/qq_43701034/article/details/86688253