5. Longest Palindromic Substring

5. Longest Palindromic Substring_第1张图片

最近再刷leetcode,除了链表之外的都用python 实现,贴出一些代码,希望指正.

问题描述:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
字符串中最长的回文数

Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.

Input: "cbbd"
Output: "bb"

解决方案.

遍历字符串,拿到一个字符,从后往前找相同的字符的位置,返回所有相同的位置索引列表,计算两个相同的字符能不能构成回文数.
用babad举例.
从b开始遍历,从abad中从后往前找b,当然这里只有一个b所以只会返回一个b的下标是2,然后计算下标从0到2是不是构成回文数,这里刚好是,计算长度,len = 3.下一个
然后遍历a同理,找到相同字符下标的位置3,那么判断下标1和3是不是构成回文数,这里也是 len = 3,继续向下遍历.
用能aaabaaaa举例.
从a开始遍历,从a之后的aabaaaa中从后往前找和a相同的字符的位置,这里相同的比较多,返回list = [7,6,5,4,2,1],那么先比较下标0到7是不是构成回文数,aaabaaaa后面的a比前面多一个,所以不是回文数,然后看0到6是不是回文数,aaabaaa刚好是,则终止判断,len = 7 继续向后遍历.
注意: python 中判断是不是回文数 return list == list[::-1]即可,list[::-1]表示翻转list

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        def is_palindromic(list):
            return list == list[::-1], len(list), list

        def find_next(list1, tar):
            # print(list1)
            list3 = []
            list2 = list1[::-1]
            # print(list2)
            for i, each in enumerate(list2):
                if each == tar:
                    list3.append(len(list1) - i)

            return list3

        max = 0
        SUBlist = ""
        if len(s) == 1:
            return s
        for i, each in enumerate(s):
            same_char_list = find_next(s[i + 1:], each)
            if same_char_list is not None and len(same_char_list) != 0:
                for each in same_char_list:
                    # print(i, i + each)
                    flag, lenght, sublist = is_palindromic(s[i:1 + i + each])
                    if flag:
                        if max < lenght:
                            max = lenght
                            SUBlist = sublist
                            if lenght == len(s):
                                return SUBlist
            else:
                if SUBlist == "":
                    SUBlist = each
        return SUBlist


solution = Solution()
print(solution.longestPalindrome("aaabaaaa"))

你可能感兴趣的:(5. Longest Palindromic Substring)