最长公共子序列

来源:互联网 发布:零基础学python张志强 编辑:程序博客网 时间:2024/05/21 09:33
#include<iostream>
#include<string>


using namespace std;


int c[100][100];


int maxVal(int x, int y){
return x>y?x:y;
}


int lcs_length(string s1,string s2){
int len1 = s1.length();
int len2 = s2.length();
for(int i=0;i<len1;++i){
for(int j=0;j<len2;++j){
c[i][j]=0;
}
}

for(int i=0;i<len1;++i){
for(int j=0;j<len2;++j){
if(s1[i]==s2[j]){
c[i+1][j+1]=c[i][j]+1;
}else{
//cout<<"s1["<<i<<"]="<<s1[i]<<", s2["<<j<<"]="<<s2[j]<<endl;

c[i+1][j+1]=maxVal(c[i+1][j],c[i][j+1]);
//cout<<c[i][j-1]<<","<<c[i-1][j]<<"  ";
//cout<<"c[i+1][j+1]="<<c[i+1][j+1]<<endl;;
}
}
}

for(int i=0;i<len1;++i){
for(int j=0;j<len2;++j){
cout<<c[i][j]<<" ";
}
cout<<endl;
}

return c[len1][len2];

}




string lcsStr(string s1, string s2){
int lcsLen = lcs_length(s1,s2);
int len1=s1.length();
int len2=s2.length();
string lcsS="";
int i=len1-1,j=len2-1;
while( i>=0&&j>=0 ){
if(s1[i]==s2[j]){
lcsS = s1[i]+lcsS;
i--;
j--;
}else{
if(c[i+1][j]>c[i][j+1]){
j--;
}else{
i--;
}
}
}
return lcsS;
}


int main(){
string s1 = "axxxbcy";
string s2 = "axbcyy";
cout<<lcsStr(s1,s2)<<endl;


return 0;
}
0 0
原创粉丝点击