这道题主要是理解俩个二维数组,以及找最大值的流程,最近考试周就先不弄详解了。有空在搞。
代码很好理解,里面的算法需要时间理解。
题目是这样的输入俩个字符串,输出最长公共子序列和长度。
#include<iostream>
#include<cstring>
using namespace std;
const int N = 100;
char s1[N],s2[N];//定义数组
int len1,len2; //数组长度
int c[N][N],b[N][N]; //c存最大长度 b存状态 1为相等,2为左大,3为上大(比较的其实是数组长度)
void LCSL(){
for(int i=1;i<=len1;i++){
for(int j=1;j<=len2;j++){
if(s1[i-1]==s2[j-1])
{ c[i][j]=c[i-1][j-1]+1;
b[i][j]=1;
}
else
{
if(c[i-1][j]>=c[i][j-1]){
c[i][j] = c[i-1][j];
b[i][j] = 2;
}
else{
c[i][j]=c[i][j-1];
b[i][j]=3;
}
}
}
}
}
void print(int i,int j){
if(i==0||j==0) return; //跳出
if(b[i][j]==1){
print(i-1,j-1); //b为1上个数是相同的
cout<<s1[i-1];
}
else if(b[i][j]==2) //b为2我们往左找
print(i,j-1);
else
print(i-1,j); //b为3我们往上找
}
int main(){
cin>>s1;
cin>>s2;
len1 = strlen(s1);
len2 = strlen(s2);
for(int i = 0;i<=len1;i++){
c[i][0]=0;//初始化
}
for(int j=0;j<=len2;j++){
c[0][j]=0;
}
LCSL();
cout<<c[len1][len2]<<endl;//最底部是最大长度
print(len1,len2); //输出最长长度的字符
return 0;
}
样例