LeetCode12.31

Longest Palindromic Substring

LeetCode12.31_第1张图片
Screen Shot 2018-12-31 at 4.42.01 PM.png

这次题目难度中等。
答案:

class Solution:
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        if not s: return s
        res = ''
        n = len(s)
        dp = [[False for _ in range(n)] for _ in range(n)]
        max = 0
        for j in range(n):
            for i in range(0, j+1):
                dp[i][j] = ((s[i] == s[j]) and ((j - i <= 2) or dp[i+1][j-1]))
                if dp[i][j]:
                    if (j-i+1) > max:
                        max = j-i+1
                        res = s[i:j+1]
        return res

这答案速度有点慢。

祝大家新年快乐。

你可能感兴趣的:(LeetCode12.31)