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 <= text1.length <= 1000
1 <= text2.length <= 1000
- The input strings consist of lowercase English characters only.
這道題讓求最長相同的子序列,注意是子序列,不是子串,所以字符並不需要相連,但是字符順序還是需要保持的。LeetCode 之前也有題目需要借助求 LCS 來解題,比如 Delete Operation for Two Strings,當時博主還疑惑怎么 LeetCode 中沒有專門求 LCS 的題呢,這不,終於補上了。解題思路和上面那道是一模一樣,若搞懂了那道題,這道也就是沒什么難度了,這里是用動態規划 Dynamic Programing 來做,使用一個二維數組 dp,其中 dp[i][j] 表示 text1 的前i個字符和 text2 的前j個字符的最長相同的子序列的字符個數,這里大小初始化為 (m+1)x(n+1)
,這里的m和n分別是 text1 和 text2 的長度。接下來就要找狀態轉移方程了,如何來更新 dp[i][j],若二者對應位置的字符相同,表示當前的 LCS 又增加了一位,所以可以用 dp[i-1][j-1] + 1 來更新 dp[i][j]。否則若對應位置的字符不相同,由於是子序列,還可以錯位比較,可以分別從 text1 或者 text2 去掉一個當前字符,那么其 dp 值就是 dp[i-1][j] 和 dp[i][j-1],取二者中的較大值來更新 dp[i][j] 即可,最終的結果保存在了 dp[m][n] 中,參見代碼如下:
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int m = text1.size(), n = text2.size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
for (int i = 1; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
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[m][n];
}
};
討論:這道題跟之前那道 Longest Palindromic Subsequence 的解題思路幾乎是一模一樣,你品,你細品,一定要通過現象看本質,才能舉一反三,觸類旁通。
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1143
類似題目:
Longest Palindromic Subsequence
Delete Operation for Two Strings
Shortest Common Supersequence
參考資料:
https://leetcode.com/problems/longest-common-subsequence/
https://leetcode.com/problems/longest-common-subsequence/discuss/348884/C%2B%2B-with-picture-O(nm)