516. Longest Palindromic Subsequence

问题

求最长的回文子序列

Input: "bbbab"
Output: 4
Explanation: One possible longest palindromic subsequence is "bbbb"

思路

dp[i][j]表示从i到j的最大回文子序列的长度。
对于dp[i][j]时,如果s[i] == s[j],显然dp[i][j]会等于dp[i+1][j-1] + 2,相当于在两头扩展相等字符。
如果不相等的话,dp[i][j] = max(dp[i+1][j], dp[i][j-1]),相当于在原来的两个dp上选一个最大的。

时间复杂度O(n2),空间复杂度O(n2)

代码

class Solution(object):
    def longestPalindromeSubseq(self, s):
        """
        :type s: str
        :rtype: int
        """
        if(s==None or s ==''):
            return 0
        if(len(s)==1):
            return 1
        dp = [[0 for _ in range(len(s))] for _ in range(len(s))]

        for i in range(len(s))[::-1]:
            dp[i][i] = 1
            for j in range(i+1,len(s)):
                if(s[i]==s[j]):
                    dp[i][j] = dp[i+1][j-1] + 2
                else:
                    dp[i][j] = max(dp[i+1][j], dp[i][j-1])
        return dp[0][len(s)-1]
posted @ 2018-10-11 11:14  PilgrimHui  阅读(272)  评论(0编辑  收藏  举报