美文网首页
516. Longest Palindromic Subsequ

516. Longest Palindromic Subsequ

作者: 一个想当大佬的菜鸡 | 来源:发表于2019-06-06 15:37 被阅读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]
    

    相关文章

      网友评论

          本文标题:516. Longest Palindromic Subsequ

          本文链接:https://www.haomeiwen.com/subject/gsluxctx.html