LeetCode5最长回文子串-Python

给定一个字符串 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

 

你可能感兴趣的:(数据结构,python)