//
// LCS最长公共自序列问题。动规解法。
#include <iostream>
#include <string.h>
#include <assert.h>
#include <time.h>
using namespace std;
int lcs(const char *str1, const char *str2)
{
assert(NULL!=str1 && NULL!=str2);
int Mlen=strlen(str1);
int Nlen=strlen(str2);
//1.分配矩阵数组
int **apn=new int *[Mlen+1];
int i;
for (i=0; i<Mlen+1; i++)
{
apn[i] = new int[Nlen+1];
}
int j;
for (i=0; i<Mlen+1; i++)
{
for (j=0; j<Nlen+1; j++)
{
apn[i][j]=0;
}
}
//2.循环
for (i=1; i<Mlen+1; i++)
{
for (j=1; j<Nlen+1; j++)
{
if (str1[i-1] == str2[j-1])
{
apn[i][j]=apn[i-1][j-1]+1;
}
else
{
int t1=apn[i-1][j];
int t2=apn[i][j-1];
apn[i][j]=(t1>t2?t1:t2);
}
}
}
int re=apn[Mlen][Nlen];
for (i=0;i<Mlen+1;i++)
{
for (j=0;j<Nlen+1;j++)
{
cout<<apn[i][j]<<" ";
}
cout<<endl;
}
// 3.销毁矩阵数组
for (i=0; i<Mlen+1; i++)
{
delete []apn[i];
}
return re;
}
int main()
{
char str1[]="abcdefghijklp";
char str2[]="asdhalfnw ";
char str3[]="acdfg";
char str4[]="acfdg";
cout<<str1<<" and "<<str2<<": "<<lcs(str1,str2)<<endl;
cout<<endl;
cout<<str3<<" and "<<str4<<": "<<lcs(str3,str4)<<endl;
return 0;
}
打印其中一个公共子串的版本:
//
// LCS最长公共自序列问题。动规解法。
#include <iostream>
#include <string.h>
#include <assert.h>
#include <time.h>
using namespace std;
int lcs(const char *str1, const char *str2)
{
assert(NULL!=str1 && NULL!=str2);
int Mlen=strlen(str1);
int Nlen=strlen(str2);
//1.分配矩阵数组
int **apn=new int *[Mlen+1];
int **apnf=new int *[Mlen+1];
int i;
for (i=0; i<Mlen+1; i++)
{
apn[i] = new int[Nlen+1];
apnf[i] = new int[Nlen+1];
}
int j;
for (i=0; i<Mlen+1; i++)
{
for (j=0; j<Nlen+1; j++)
{
apn[i][j]=0;
apnf[i][j]=0;
}
}
//2.循环
for (i=1; i<Mlen+1; i++)
{
for (j=1; j<Nlen+1; j++)
{
if (str1[i-1] == str2[j-1])
{
apn[i][j]=apn[i-1][j-1]+1;
apnf[i][j]=1; // 斜对角方向
}
else
{
int t1=apn[i-1][j];
int t2=apn[i][j-1];
apn[i][j]=(t1>t2?t1:t2);
if(t1>t2)
apnf[i][j]=2; // 竖直方向
else
apnf[i][j]=3; // 水平方向
}
}
}
int re=apn[Mlen][Nlen];
for (i=0;i<Mlen+1;i++)
{
for (j=0;j<Nlen+1;j++)
{
cout<<apn[i][j]<<" ";
}
cout<<endl;
}
//3.打印
i=Mlen;
j=Nlen;
while(true)
{
if (apnf[i][j]==2 )
{
i--;
continue;
}else if (apnf[i][j]==3)
{
j--;
continue;
}else if (apnf[i][j]==1)
{
cout<<str1[i-1]<<" ";
i--;j--;
}
if (i==0 || j==0)
{
break;
}
}
cout<<endl;
// 4.销毁矩阵数组
for (i=0; i<Mlen+1; i++)
{
delete []apn[i];
delete []apnf[i];
}
return re;
}
int main()
{
char str1[]="abcdefghijklpn";
char str2[]="asdhalfnw ";
char str3[]="acdfg";
char str4[]="acfdg";
cout<<str1<<" and "<<str2<<": "<<lcs(str1,str2)<<endl;
cout<<endl;
cout<<str3<<" and "<<str4<<": "<<lcs(str3,str4)<<endl;
return 0;
}
参考: