1 题目
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.
2 尝试解
2.1 分析
给定两个字符串A和B,求两个字符串的最长公共子序列的长度。
计A的长度和B的长度分别为m和n。考虑A[m]和B[n]:
A[m] == B[n],则存在一个最长公共子序列,A[m]和B[n]在其中。证明:如果A[m]和B[n]都不在最长公共子序列中,可以添加进去,子序列还可以再延长,矛盾。所以A[m]和B[n]至少有一个在其中。如果A[m]在其中,而B[n]不在,可以用B[n]替代B中最长公共子序列的末尾,同理,A[m]不在其中,而B[n]在其中,也可用A[m]替换,证明完毕。所以问题转化为寻找A[m-1]和B[n-1]的最长公共子序列,再分别加上A[m]和B[n]。
A[m] != B[n],如果A[m]和B[n]都不在任何最长公共子序列中,则直接删去无影响。如果A[m]在最长公共子序列中,那么说明存在k<n,A[m] = B[k]。由于公共子序列以B[k]结尾,删除其后的元素无影响,所以问题转化为求A[:m]和B[:n-1]的最长公共子序列。如果B[n]在最长公共子序列中,问题转化为A[:m-1]和B[:]的最长公共子序列。
用F(m,n)表示字符串A[:m]和B[:n]的最长公共子序列的长度,则
A[m] == B[n] F(m,n) = F(m-1,n-1)+1
A[m] != B[n] F(m,n) = max(F(m-1,n) , F(m,n-1))
2.2 代码
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
if(!text1.size()||!text2.size()) return 0;
vector<vector<int>> record(text1.size(),vector<int>(text2.size(),0));
for(int i = 0; i < text1.size(); i++){
for(int j = 0; j < text2.size(); j++){
if(text1[i]==text2[j]){
record[i][j] = (i>0&&j>0?record[i-1][j-1]:0)+1;
}
else{
record[i][j] = max((i>0?record[i-1][j]:0),(j>0?record[i][j-1]:0));
}
}
}
return record.back().back();
}
};
3 标准解
3.1 分析
3.2 代码
class Solution {
public:
int longestCommonSubsequence(string &a, string &b) {
vector<vector<short>> m(a.size() + 1, vector<short>(b.size() + 1));
for (auto i = 1; i <= a.size(); ++i)
for (auto j = 1; j <= b.size(); ++j)
if (a[i - 1] == b[j - 1]) m[i][j] = m[i - 1][j - 1] + 1;
else m[i][j] = max(m[i - 1][j], m[i][j - 1]);
return m[a.size()][b.size()];
}
};