/*
要点:如果s1[i] == s2[j] 返回lcs(i-1, j-1)+1
否则,返回lcs(i-1, j)和lcs(i, j-1)的较大者
*/
#include <iostream>
using namespace std;
const int MAX_SIZE = 10;
char s1[] = "BDCABA";
char s2[] = "ABCBDAB";
int dp[MAX_SIZE][MAX_SIZE] = {0};
int path[MAX_SIZE][MAX_SIZE] = {0};
int lcs()
{
int len1 = strlen(s1);
int len2 = strlen(s2);
int i, j;
for (i = 1; i <= len1; ++i){
for (j = 1; j <= len2; ++j){
if (s1[i-1] == s2[j-1]){
dp[i][j] = dp[i-1][j-1] + 1;
path[i][j] = 0;
}
else{
if (dp[i-1][j] > dp[i][j-1]){
dp[i][j] = dp[i-1][j];
path[i][j] = -1;
}
else{
dp[i][j] = dp[i][j-1];
path[i][j] = 1;
}
}
}
}
//回溯
i = len1;
j = len2;
while (i > 0 && j > 0){
if (path[i][j] == 0){
cout<<s1[i-1];
i--;
j--;
}
else if (path[i][j] == -1){
i--;
}
else{
j--;
}
}
cout<<endl;
return dp[len1][len2];
}
int main()
{
cout<<lcs()<<endl;
return 0;
}
最长公共子串
最新推荐文章于 2023-04-18 23:37:02 发布