LeetCode 5. Longest Palindromic Substring

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/y12345678904/article/details/79946202

题目

这里写图片描述

思路

dp,构造上三角矩阵。

代码

class Solution:
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if not s: return null
        length = len(s)
        #init
        dp = [[0 for i in range(length)] for j in range(length)]
        #update dp
        for i in range(length)[::-1]:
            for j in range(i, length):
                if i == j:
                    dp[i][j] = 1
                    continue
                if s[i] == s[j]:
                    if j == i + 1:
                        dp[i][j] = 2
                    elif dp[i + 1][j - 1]:
                        dp[i][j] = dp[i + 1][j - 1] + 2
        maxi = 0; maxj = 0; maxNum = 0
        for i in range(length):
            for j in range(i, length):
                if dp[i][j] > maxNum:
                    maxi = i; maxj = j; maxNum = dp[i][j]
        return s[maxi:maxj + 1]
阅读更多

扫码向博主提问

sparksnail

非学,无以致疑;非问,无以广识
去开通我的Chat快问
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页