算法: 最长公共子串1143. Longest Common Subsequence

Posted 架构师易筋

tags:

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

1143. Longest Common Subsequence

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

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.

For example, “ace” is a subsequence of “abcde”.
A common subsequence of two strings is a subsequence that is common to both strings.

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, text2.length <= 1000
  • text1 and text2 consist of only lowercase English characters.

扩展为2维表格,动态规划解法

让X是“XMJYAUZ”和Y是“MZJAWXU”。X和之间的最长公共子序列Y是“MJAU”。下表显示了X和前缀之间的最长公共子序列的长度Y。的ith行和jth列显示之间的LCS的长度X_{1…i}和Y_{1…j}。

 public int longestCommonSubsequence(String s1, String s2) {
        int[][] dp = new int[s1.length() + 1][s2.length() + 1];
        for (int i = 0; i < s1.length(); ++i)
            for (int j = 0; j < s2.length(); ++j)
                if (s1.charAt(i) == s2.charAt(j)) dp[i + 1][j + 1] = 1 + dp[i][j];
                else dp[i + 1][j + 1] =  Math.max(dp[i][j + 1], dp[i + 1][j]);
        return dp[s1.length()][s2.length()];
    }

Time & space: O(m * n)

优化存储空间

进一步空间优化以节省一半空间
显然,上面方法2中的代码只需要前一行的前一列和当前列的信息来更新当前行。因此,我们只需使用一个1行一维数组和2变量,以保存和更新匹配结果为字符text1和text2。

public int longestCommonSubsequence(String text1, String text2) {
        int m = text1.length(), n = text2.length();
        if (m < n) {
            return longestCommonSubsequence(text2, text1);
        }
        int[] dp = new int[n + 1];
        for (int i = 0; i < text1.length(); ++i) {
            for (int j = 0, prevRow = 0, prevRowPrevCol = 0; j < text2.length(); ++j) {
                prevRowPrevCol = prevRow;
                prevRow = dp[j + 1];
                dp[j + 1] = text1.charAt(i) == text2.charAt(j) ? prevRowPrevCol + 1 : Math.max(dp[j], prevRow);
            }
        }
        return dp[n];
    }

Time: O(m * n). space: O(min(m, n)).

参考

https://leetcode.com/problems/longest-common-subsequence/discuss/351689/JavaPython-3-Two-DP-codes-of-O(mn)-and-O(min(m-n))-spaces-w-picture-and-analysis

以上是关于算法: 最长公共子串1143. Longest Common Subsequence的主要内容,如果未能解决你的问题,请参考以下文章

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

算法:最长子序列1143. Longest Common Subsequence

LeetCode 1143 最长公共子序列

LeetCode 1143 最长公共子序列

[PHP]算法-最长公共子串的PHP实现

14. Longest Common Prefix 最长公共前缀子串