1143. Longest Common Subsequence(Medium)

Given two strings text1 and text2, return the length of their longest common subsequence.

subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.

 

If there is no common subsequence, return 0.

 

题意:

给定两个字符串 text1 和 text2,返回这两个字符串的最长公共子序列的长度。

本文考虑动态规划的方法

 

C[i,j]表示:(x1,x2,...,xi)和(y1,y2,...,yj)的最长公共子序列的长度;
# 1143. Longest Common Subsequence

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        # m = len(text1)
        # n = len(text2)
        m, n = len(text1), len(text2)

        if text1.isspace() | text2.isspace():
            return 0
        # dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
        dp = [[0 * (n+1)] for _ in range(m+1)]

        for i in range(1, m+1):
            for j in range(1, n+1):
                if text1[i-1] == text2[j-1]:
                    dp[i][j] = dp[i-1][j-1] + 1
                else:
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1])
        
        return dp[-1][-1]

  

posted @ 2020-12-02 14:39  Yancea  阅读(99)  评论(0编辑  收藏  举报