LeetCode 题解系列(1143):最长公共子序列

题目描述:

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

一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
例如,”ace” 是 “abcde” 的子序列,但 “aec” 不是 “abcde” 的子序列。两个字符串的「公共子序列」是这两个字符串所共同拥有的子序列。

若这两个字符串没有公共子序列,则返回 0。

示例 1:

输入:text1 = “abcde”, text2 = “ace”
输出:3
解释:最长公共子序列是 “ace”,它的长度为 3。
示例 2:

输入:text1 = “abc”, text2 = “abc”
输出:3
解释:最长公共子序列是 “abc”,它的长度为 3。
示例 3:

输入:text1 = “abc”, text2 = “def”
输出:0
解释:两个字符串没有公共子序列,返回 0。  

提示:

1 <= text1.length <= 1000
1 <= text2.length <= 1000
输入的字符串只含有小写英文字符。

解法一: 动态规划

  1. 建立动态规划矩阵 dp[len1][len2],dp[i][j] 代表 text1[0..i] 和 text2[0..j] 的最长公共子序列长度。
  2. base case:dp[0][0] 只有在text1[0]==text2[0]时才会为 1,并且第一行,只有在某个 text1[i]==text2[0]之后,全为 1,否则为 0;第一列同理。
  3. 一般位置:dp[i][j] 判断的是 text1[0..i] 和 text2[0..j],如果 text1[i]==text2[j],那么直接比较 text1[0..i-1] 和 text2[0..j-1] 的长度然后+1;如果不相等,代表等价于寻找text1[0..i-1] 与 text2[0..j] 和 text1[0..i] 与 text2[0..j-1] 两者中较长的序列作为结果,即去除 text1 或 text2 末尾一个元素不影响结果。
  4. 结果就是 dp[len1-1][len2-1]

时间复杂度: O(mn); 辅助空间复杂度: O(mn)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
if (text1 == null || text2 == null || text1.length() == 0 || text2.length() == 0) {
return 0;
}
int len1 = text1.length();
int len2 = text2.length();
int[][] dp = new int[len1][len2];
dp[0][0] = text1.charAt(0) == text2.charAt(0) ? 1 : 0;
// 初始化 dp 矩阵
for (int i = 1; i < len1; i++) {
dp[i][0] = text1.charAt(i) == text2.charAt(0) ? 1 : dp[i-1][0];
}
for (int j = 1; j < len2; j++) {
dp[0][j] = text2.charAt(j) == text1.charAt(0) ? 1 : dp[0][j-1];
}
// 一般位置
for (int i = 1; i < len1; i++) {
for (int j = 1; j < len2; j++) {
if (text1.charAt(i) == text2.charAt(j)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[len1 - 1][len2 - 1];
}
}

LeetCode 题解系列(1143):最长公共子序列
http://example.com/2020/07/16/D-DataStructureAndAlgorithm/D-LeetCode/1143-LongestCommonSubsequence/
作者
ChenXi
发布于
2020年7月16日
许可协议