【LeetCode刷题之旅】005 Longest Palindromic Substring 【Python】

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

输入"cbbd"

预期结果

"bb"

# -*- coding: utf-8 -*-
# @Time    : 2019/1/15 10:04
# @Author  : Jeloys
# @FileName: 005_Longest Palindromic Substring_1.py
# @Software: PyCharm

'''
这道题。如何划分小问题,我们可以先把所有长度最短为1的子字符串计算出来,
根据起始位置从左向右,这些必定是回文。然后计算所有长度为2的子字符串,
再根据起始位置从左向右。到长度为3的时候,我们就可以利用上次的计算结果:
如果中心对称的短字符串不是回文,那长字符串也不是,如果短字符串是回文,
那就要看长字符串两头是否一样。这样,一直到长度最大的子字符串,我们就把整个字符串集穷举完了。


'''
class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        # 使用动态规划,用空间换时间,把问题拆分
        # 获取字符串s的长度
        str_length = len(s)
        # 记录最大字符串长度
        max_length = 0
        # 记录位置
        start = 0
        # 循环遍历字符串的每一个字符
        for i in range(str_length):
            # 如果当前循环次数-当前最大长度大于等于1  并  字符串[当前循环次数-当前最大长度-1:当前循环次数+1]  == 取反后字符串
            if i - max_length >= 1 and s[i-max_length-1: i+1] == s[i-max_length-1: i+1][::-1]:
                # 记录当前开始位置
                start = i - max_length - 1
                # 取字符串最小长度为2,所以+=2,s[i-max_length-1: i+1]
                max_length += 2
                continue
            # 如果当前循环次数-当前最大长度大于等于0  并  字符串[当前循环次数-当前最大长度:当前循环次数+1]  == 取反后字符串
            if i - max_length >= 0 and s[i-max_length: i+1] == s[i-max_length: i+1][::-1]:
                start = i - max_length
                # 取字符串最小长度为1,所以+=1,s[i-max_length: i+1]
                max_length += 1
        # 返回最长回文子串
        return s[start: start + max_length]


if __name__ == '__main__':
    s = "aa"
    # s = "cbbd"
    sl = Solution()
    print(sl.longestPalindrome(s))

转载自https://blog.csdn.net/chenhua1125/article/details/80395873

猜你喜欢

转载自blog.csdn.net/weixin_38371360/article/details/86489999