題目描述
給定兩個字符串 text1 和 text2,返回這兩個字符串的最長公共子序列的長度。
一個字符串的 子序列 是指這樣一個新的字符串:它是由原字符串在不改變字符的相對順序的情況下刪除某些字符(也可以不刪除任何字符)后組成的新字符串。
例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。兩個字符串的「公共子序列」是這兩個字符串所共同擁有的子序列。
若這兩個字符串沒有公共子序列,則返回 0。
示例:
輸入:text1 = "abcde", text2 = "ace"
輸出:3
解釋:最長公共子序列是 "ace",它的長度為 3。
輸入:text1 = "abc", text2 = "abc"
輸出:3
解釋:最長公共子序列是 "abc",它的長度為 3。
輸入:text1 = "abc", text2 = "def"
輸出:0
解釋:兩個字符串沒有公共子序列,返回 0。
說明:
- 1 <= text1.length <= 1000
- 1 <= text2.length <= 1000
- 輸入的字符串只含有小寫英文字符。
題目鏈接: https://leetcode-cn.com/problems/longest-common-subsequence/
思路
這題是最長公共子串問題,也被稱為 LCS (Longest Common Subsequence)問題,可以使用動態規划來做。假設兩個字符串分別為 text1 和 text2:
- 狀態定義:dp[i][j] 表示 text1 在 [0, i] 范圍內的子串和 text2 在 [0, j] 范圍內的子串的 LCS;
- 狀態轉移:
- 如果 text1[i-1]==text2[j-1],那么說明我們找到了公共子串中的一個字符,則 dp[i][j] = dp[i-1][j-1] + 1;
- 否則,如果 text1[i-1]!=text2[j-1],則 dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
- 邊界條件:如果兩個字符串有一個為空,則 LCS 的長度就為 0,也就是 dp[0][.] = dp[.][0] = 0;
代碼如下:
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
if(text1.empty() || text2.empty()) return 0;
int m = text1.size();
int n = text2.size();
vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
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];
}
};
我們注意到,兩個字符串的長度分別是 m 和 n,但是 dp 數組的形狀是 dp[m+1][n+1],這樣做相當於分別在兩個字符串開頭添加了空串,能簡化代碼。不添加空串的代碼可參考這篇題解。
- 時間復雜度:O(mn)
- 空間復雜度:O(mn)
拓展
假如題目不要求返回最長公共子串的長度,而要求返回具體的公共子串。這種情況下,我們可以設置兩個變量:end 表示公共子串在 text2 的結尾的位置,maxLen 記錄公共子串的長度。當計算出新的 dp[i][j] 時,如果 dp[i][j]>maxLen,則我們更新 maxLen 為 dp[i][j],並且設置 end 為 j-1。循環結束時,如果 maxLen=0,則返回空串,否則,返回 text2.substr(end-maxLen+1, maxLen) 即可。
代碼如下:
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
if(text1.empty() || text2.empty()) return 0;
int end = 0;
int maxLen = 0;
int m = text1.size();
int n = text2.size();
vector<vector<int>> dp(m+1, vector<int>(n+1, 0));
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]);
if(dp[i][j]>maxLen){
maxLen = dp[i][j];
end = j-1;
}
}
}
if(maxLen==0) return "";
else return text2.substr(end-maxLen+1, maxLen);
}
};