516. Longest Palindromic Subsequ

2019-06-06  本文已影响0人  一个想当大佬的菜鸡
516. Longest Palindromic Subsequence

用dp[i][j]表示i到j的最长回文
如果i和j相等,就是dp[i+1][j-1]+2
否则i和j对结果没贡献,等于dp[i+1][j]或dp[i][j-1]

class Solution(object):
    def longestPalindromeSubseq(self, s):
        """
        :type s: str
        :rtype: int
        """
        m = len(s)
        if m <= 1:
            return m
        dp = [[0 for i in range(m)] for j in range(m)]
        for j in range(m):
            dp[j][j] = 1
            for i in range(j-1, -1, -1):
                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][m-1]
class Solution(object):
    def longestPalindromeSubseq(self, s):
        """
        :type s: str
        :rtype: int
        """ 
        m = len(s)
        if m <= 1:
            return m
        dp = [[0 for i in range(m)] for j in range(m)]
        for i in range(m-1,-1,-1):
            dp[i][i] = 1
            for j in range(i+1,m):
                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][m-1]
上一篇下一篇

猜你喜欢

热点阅读