LeetCode-Python-5. 最长回文子串

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

示例 1:

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

示例 2:

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

第一种思路:

找出所有的子串,判断是否回文,记录最长的。

太慢了,会卡在第80个case。

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        #把所有的子串找出来,判断回文,刷新最长
        max_l = 0
        res = ""
        for i in range(0, len(s)):
            for j in range(i, len(s)):
                substring = s[i:j + 1]
                
                if substring == substring[::-1]:
                    # print substring, j + 1 - i, max_l
                    if max_l < j + 1 - i:
                        max_l = j + 1 - i
                        res = substring
                        
        return res

第二种思路:

中心扩散法。

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        max_l = 0
        res = ""
        for i in range(0, len(s)):
            #以s[i] 为中心向左右扩散
            left, right = i, i
            while(left >= 0 and right < len(s) and s[left] == s[right]):
                if max_l < right - left + 1:
                    max_l = right - left + 1
                    res = s[left:right + 1]
                left -= 1
                right += 1
                        
            #以s[i],s[i+1]为中心向左右扩散
            left, right = i, i + 1
            while(left >= 0 and right < len(s) and s[left] == s[right]):
                if max_l < right - left + 1:
                    max_l = right - left + 1
                    res = s[left:right + 1]
                left -= 1
                right += 1            
        return res

 

你可能感兴趣的:(Leetcode,Python)