<pre name= "code" class= "CPP" >/* * Copyleft@hustyangju * question: Longest common subsequece problem * idea: from bottom to top, using dynamic programming, dividing sub- Problem, using the length variation of the LCS sub-problem to obtain the LCS * Time complexity O (m*n) * Space complexity O (m*n) * * #include <iostream>//#include <string> using Namespac
e std;
Class LCS {Public:lcs (char *a,int m, char *b, int n): _a (a), A_length (M), _b (b), B_length (n)//pass two strings, and pass their length {
for (int i=0;i<100;i++) {for (int j=0;j<100;j++) count[i][j]=0; } if (max (sizeof (a), sizeof (b)) >100) cout<< "error! COUNT[100][100] Too small! "
<<endl;
} ~lcs () {if (_a!=null) {delete _a;
_a=null;
} if (_b!=null) {delete _b;
_b=null;
}} void Get_lcs (); Private:char *_a; string one int a_length; Length char *_b; string two int b_length; length int count[100][100];
LCS length Two-dimensional state array}; /* 0 i=0 or j=0 * *count[i][j]= count[i-1][j-1]+1 x[i-1] ==y[j-1] and I, j>0 * * MAX (count[i-1][j],count[i][j-1]) x[i-1]!=y[j-1] and I, j>0 */void Lcs::get
_lcs () {int m=a_length;
int n=b_length;
for (int i=1;i<=m;i++) {for (int j=1;j<=n;j++) {if (* (_a+i-1) ==* (_b+j-1)) {
count[i][j]=count[i-1][j-1]+1;
} else if (Count[i-1][j]>=count[i][j-1]) {count[i][j]=count[i-1][j];
} else count[i][j]=count[i][j-1]; }//FOR}/* Print LCS length two-dimensional array */for (int i=1;i<=m;i++) {for (int j=1;j<=n;j++) cout<&
lt;count[i][j]<< "";
cout<<endl;
}/*LCS Length */cout<< "LCS Length:" <<count[m][n]<<endl; /* Output LCS, here is a tip, which is to increase the length of one string and the other for the entire string comparison, the length of the LCS increasesAdd 1 to indicate that the location is a character of LCS */cout<< "LCS is:" <<endl;
for (int p=1;p<=n;p++) {if (count[m][p]-count[m][p-1]==1) cout<<* (_b+p-1) << "";
} cout<<endl;
} int main () {char a[]= "Abcbdab";
cout<<a<<endl;
Char b[]= "BECBD";
cout<<b<<endl;
LCS Mylcs (A,sizeof (a) -1,b,sizeof (b)-1);
Mylcs.get_lcs ();
}
Results: