题目描述
给定两个字符串str1和str2,输出两个字符串的最长公共子序列。如果最长公共子序列为空,则输出-1。
示例1
输入
"1A2C3D4B56","B1D23CA45B6A"
返回值
"123456"
说明
"123456"和“12C4B6”都是最长公共子序列,任意输出一个。
1、先求出最长公共子序列长度
2、再求出子序列
class Solution {
public:
/**
* longest common subsequence
* @param s1 string字符串 the string
* @param s2 string字符串 the string
* @return string字符串
*/
string LCS(string s1, string s2) {
// write code here
string res;
int len1=s1.length();
int len2=s2.length();
int dp[len1+1][len2+1]; //dp[i][j]表示0~i-1(前i个)与0~j-1(前j个)字符的最长公共子串长度
memset(dp,0,sizeof(dp));
//求最长公共子串的长度
for(int i=1;i<=len1;++i) //******注意范围*********
for(int j=1;j<=len2;++j){
if(s1[i-1]==s2[j-1]) //******注意第i个字符的表示*******
dp[i][j]=dp[i-1][j-1]+1;
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
//求出具备dp[len1][len2]长度的子串
if(dp[len1][len2]==0)
return "-1";
int i=len1,j=len2;
while(i>0 && j>0){
if(dp[i][j]==dp[i-1][j]){ //说明s1中第i-1个字符不属于(最长)公共子串
i--;
continue;
}
if(dp[i][j]==dp[i][j-1]){ //说明s2中第j-1个字符不属于(最长)公共子串
j--;
continue;
}
res.push_back(s1[i-1]); //******注意第i个字符的表示*******
i--;
j--;
}
reverse(res.begin(),res.end()); //*****反序即可******
return res;
}
};