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.
给定两个字符串text1和text2,返回它们最长的公共子序列的长度。
字符串的子序列是从原始字符串生成的新字符串,其中删除了一些字符(可以是一个字符),而不会更改其余字符的相对顺序。 (例如,“ ace”是“ abcde”的子序列,而“ aec”则不是)。 两个字符串的公共子序列是两个字符串共有的子序列。
如果没有公共子序列,则返回0。
这里一开始没看懂题目,试了几次,才发现意思是text1和text2的子序列是可以跳过它们任何的字符,但是必须按顺序。
比如text1="abcd" text2="dadc" result="ac" 输出2
题目乍一看很简单,实际上加了刚刚我发现的限制以后,就不能简单的判断了。这里用暴力法能做,但是会超时,所以只能动态规划,想到这点应该就不难了。
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int t1_len = text1.length(), t2_len = text2.length();
if(!(t1_len & t2_len))
return 0;
vector<int> buffer(t2_len, 0);
vector<vector<int>> result_table(t1_len, buffer);
for(int i2 = 0; i2 < text2.length(); i2++){
for(int i1 = 0; i1 < text1.length(); i1++){
if(text1[i1] == text2[i2]){
if(i1 > 0 && i2 > 0)
result_table[i1][i2] = result_table[i1 - 1][i2 - 1] + 1;
else
result_table[i1][i2] = 1;
}
else{
if(i1 > 0 && i2 > 0)
result_table[i1][i2] = max(result_table[i1 - 1][i2], result_table[i1][i2 - 1]);
else if(i1 > 0)
result_table[i1][i2] = result_table[i1 - 1][i2];
else if(i2 > 0)
result_table[i1][i2] = result_table[i1][i2 - 1];
else
result_table[i1][i2] = 0;
}
}
}
return result_table[t1_len - 1][t2_len - 1];
}
};