給定兩個字符串 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
輸入的字符串只含有小寫英文字符。
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int len1 = text1.size();
int len2 = text2.size();
if(len1==0 || len2==0)
return 0;
vector<vector<int>> dp(len1+1,vector<int> (len2+1,0));
for(int i=1;i<=len1;++i)
for(int j=1;j<=len2;++j)
{
dp[i][j] = max3(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]+(text1[i-1]==text2[j-1]));//注意text1下標是i-1
}
return dp[len1][len2];
}
int max3(int i,int j,int k){
return max(i,max(j,k));
}
};