//LCS
#include<iostream>
#include<string>
using namespace std;
void LCS_Length(string x,string y,int (*c)[100],int (*b)[100])
{
int m,n;
m=x.length();
n=x.length();
int i,j;
//如果i或j等於0則c[i][j]=0;
for(i=1;i<=m;i++)
{
c[i][0]=0;
}
for(i=1;i<=n;i++)
{
c[0][i]=0;
}
//遍歷兩個字符串,依次標記c[i][j],c[i][j]標記了從x的開始到第i個元素與從
//y開始到第j個元素中LCS的長度
//數組b用來標記最長公共子串所要走的路線,該路線爲兩個字符串組成的矩陣中的對應的字母
for(i=1;i<=m;i++)
{
for(j=1;j<=n;j++)
{
if(x[i-1]==y[j-1])
{
c[i][j]=c[i-1][j-1]+1;
//代替箭頭指向左上
b[i][j]=1;
}
else
{
if(c[i][j-1]>=c[i-1][j])
{
c[i][j]=c[i][j-1];
//代替箭頭指左
b[i][j]=2;
}
else
{
c[i][j]=c[i-1][j];
//代替箭頭指向上
b[i][j]=3;
}
}
}
}
}
void PrintAnswer(string x,int(*b)[100],int i,int j)
{
if(i==0||j==0)
{
return ;
}
else
{
if(b[i][j]==1)
{
PrintAnswer(x,b,i-1,j-1);
cout<<x[i-1]<<" ";
}
else if(b[i][j]==2)
{
PrintAnswer(x,b,i,j-1);
}
else
{
PrintAnswer(x,b,i-1,j);
}
}
}
int main()
{
string x="abcbda";
string y="bdcaba";
int c[100][100]={0};
int b[100][100]={0};
LCS_Length(x,y,c,b);
cout<<"the LCS is: "<<c[x.length()][y.length()]<<endl;
PrintAnswer(x,b,x.length(),y.length());
return 0;
}
—————————————————————————————————
本文原創自Slience的csdn技術博客。
本博客所有原創文章請以鏈接形式註明出處。
歡迎關注本技術博客,本博客的文章會不定期更新。
大多數人想要改造這個世界,但卻罕有人想改造自己。
世上沒有絕望的處境,只有對處境絕望的人。
————By slience
—————————————————————————————————