python 667. 最长的回文序列 longest-palindromic-subsequence

class Solution:
    """
    @param s: the maximum length of s is 1000
    @return: the longest palindromic subsequence's length
    """
    def longestPalindromeSubseq(self, s):
        # write your code here
        if s == s[::-1]:
            return len(s)
        dp = [[1 for i in range(len(s))] for j in range(len(s))]
        for j in (range(len(s))):
            for i in range(j - 1, -1, -1):
                if s[i] == s[j]:
                    dp[i][j] = 2 + dp[i + 1][j - 1] if i + 1 <= j - 1 else 2
                else:
                    dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
        return dp[0][len(s) - 1]   
        使用动态规划

猜你喜欢

转载自blog.csdn.net/zlsjsj/article/details/80605596
今日推荐