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

示例 1:

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

示例 2:

输入: \"cbbd\"
输出: \"bb\"
class Solution:
    def longestPalindrome(self, s):
        \"\"\"
        :type s: str
        :rtype: str
        \"\"\"
        #最长回文串必然在最长公共子串中,从第一个字符开始,判断其是否为会问字符串
        length = len(s)
        result = \"\"
        if length == 0 or length == 1:
            return s
        for i in range(length):
            string = self.issub(s, i, length)
            if len(string) > len(result):
                result = string
        return result
    
    def issub(self, s, i, length):
        j = 0
        string1 = \"\"
        string2 = \"\"
        while(i - j >= 0 and i + j < length): ##回文串为奇数个
            if s[i - j] != s[i + j]:
                break
            else:
                j += 1  
        if j != 0:
            string1 = s[i - j + 1 : i + j]
        else:
            string1 = s[i]
        k = 0
        while(i - k >= 0 and i + k + 1< length): ##回文串为偶数个
            if s[i - k] != s[i + k + 1]:
                break
            else:
                k += 1
        if k != 0:
            string2 = s[i - k + 1 : i + k + 1]
        if len(string1) > len(string2):
            string = string1
        else:
            string = string2
        return string

 

收藏 打印