LeetCode解题分享:1143. Longest Common Subsequence

Problem

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

A 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.

Example 1:

Input: text1 = “abcde”, text2 = “ace”
Output: 3
Explanation: The longest common subsequence is “ace” and its length is 3.

Example 2:

Input: text1 = “abc”, text2 = “abc”
Output: 3
Explanation: The longest common subsequence is “abc” and its length is 3.

Example 3:

Input: text1 = “abc”, text2 = “def”
Output: 0
Explanation: There is no such common subsequence, so the result is 0.

Constraints:

  1. 1 <= text1.length <= 1000
  2. 1 <= text2.length <= 1000
  3. The input strings consist of lowercase English characters only.
解题思路

   这是一道很典型的动态规划题目。对于这种关于计算两个字符串之间的关系的题,大多都是定义一个二维数组, 数组中的每个元素都表示一个状态。对于这一题,我们可以定义一个二维数组 d p [ i ] [ j ] dp[i][j] dp[i][j],数组中的每一个元素表示当前状态(即text1的前 i i i个字符和text2的前 j j j个字符可以计算得出的最长子字符串,需要注意的是这里的 i i i j j j并不包括在内。)下最长相同子字符串的长度, 那么下一步就应该分析状态转移方程。

   很明显,当我们扫描到text1的第 i i i个字符,text2的第 j j j个字符时,需要考虑这两个字符是否相等,如果这两个字符相等,很明显,计算出的结果应该是text1的前 i − 1 i - 1 i1和text2的前 j − 1 j - 1 j1个计算出的最长子字符串的长度加1,即:
d p [ i ] [ j ] = d p [ i − 1 ] [ j − 1 ] + 1 dp[i][j] = dp[i - 1][j - 1] + 1 dp[i][j]=dp[i1][j1]+1

   当两个字符不相等时,我们就需要考虑 d p [ i − 1 ] [ j ] dp[i - 1][j] dp[i1][j]以及 d p [ i ] [ j − 1 ] dp[i][j - 1] dp[i][j1],因为当前的两个字符已经不相等了,所以我们没有办法在原有的基础上更进一步,只能在 d p [ i − 1 ] [ j ] dp[i - 1][j] dp[i1][j]以及 d p [ i ] [ j − 1 ] dp[i][j - 1] dp[i][j1]中选择一个最大值,即:
d p [ i ] [ j ] = m a x ( d p [ i − 1 ] [ j ] , d p [ i ] [ j − 1 ] ) dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) dp[i][j]=max(dp[i1][j],dp[i][j1])

   代码如下:

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        rows = len(text1) + 1
        cols = len(text2) + 1
        dp = [[0 for i in range(cols)] for j in range(rows)]

        for i in range(1, rows):
            for j in range(1, cols):
                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]

你可能感兴趣的:(LeetCode)