leetcode1143. Longest Common Subsequence

Posted seyjs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1143. Longest Common Subsequence相关的知识,希望对你有一定的参考价值。

题目如下:

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.

 

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 <= text1.length <= 1000
  • 1 <= text2.length <= 1000
  • The input strings consist of lowercase English characters only.

解题思路:典型的动态规划场景。记dp[i][j]为text1的[0~i]区间,text2[0~j]区间内最长的公共子序列的长度。那么显然有: 如果 text1[i] == text2[j],dp[i][j] = max(dp[i][j],dp[i-1][j-1]+1);又如果 text1[i] != text2[j],有 dp[i][j] = max(dp[i][j],dp[i-1][j-1],dp[i-1][j],dp[i][j-1])。

代码如下:

class Solution(object):
    def longestCommonSubsequence(self, text1, text2):
        """
        :type text1: str
        :type text2: str
        :rtype: int
        """
        dp = [[0]* len(text2) for _ in text1]
        for i in range(len(text1)):
            for j in range(len(text2)):
                if text1[i] == text2[j]:
                    dp[i][j] = 1
                    if i > 0 and j > 0:
                        dp[i][j] = max(dp[i][j],1+dp[i-1][j-1])
                else:
                    if i > 0 and j > 0:
                        dp[i][j] = max(dp[i][j],dp[i-1][j-1])
                    if i > 0:
                        dp[i][j] = max(dp[i][j],dp[i-1][j])
                    if j > 0:
                        dp[i][j] = max(dp[i][j],dp[i][j-1])
        #print dp
        return dp[-1][-1]

 

以上是关于leetcode1143. Longest Common Subsequence的主要内容,如果未能解决你的问题,请参考以下文章

1143. Longest Common Subsequence

leetcode1143 Longest Common Subsequence

leetcode1143. Longest Common Subsequence

leetcode 1143. Longest Commom Subsequence 最长公共子序列(中等)

LeetCode 1143 最长公共子序列

LeetCode 1143 最长公共子序列