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

痛定思痛。 2022-09-17 03:28 277阅读 0赞

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:

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

Example 2:

  1. Input: text1 = "abc", text2 = "abc"
  2. Output: 3
  3. Explanation: The longest common subsequence is "abc" and its length is 3.

Example 3:

  1. Input: text1 = "abc", text2 = "def"
  2. Output: 0
  3. 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}。

在这里插入图片描述

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

Time & space: O(m * n)

优化存储空间

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

  1. public int longestCommonSubsequence(String text1, String text2) {
  2. int m = text1.length(), n = text2.length();
  3. if (m < n) {
  4. return longestCommonSubsequence(text2, text1);
  5. }
  6. int[] dp = new int[n + 1];
  7. for (int i = 0; i < text1.length(); ++i) {
  8. for (int j = 0, prevRow = 0, prevRowPrevCol = 0; j < text2.length(); ++j) {
  9. prevRowPrevCol = prevRow;
  10. prevRow = dp[j + 1];
  11. dp[j + 1] = text1.charAt(i) == text2.charAt(j) ? prevRowPrevCol + 1 : Math.max(dp[j], prevRow);
  12. }
  13. }
  14. return dp[n];
  15. }

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

发表评论

表情:
评论列表 (有 0 条评论,277人围观)

还没有评论,来说两句吧...

相关阅读