编辑代码

#include <iostream>
#include <cstring>
using namespace std;
const int N=1024;
int c[N][N];
int maxLen=0,flag=0;
char s1[N],s2[N];
int len1,len2;
void LCSs()
{
    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;
                if(c[i][j] > maxLen){
                    maxLen = c[i][j];
                    flag = j;  
                }
            }
            else{
                c[i][j] = 0;
            }

        }
    }
}

void PRINT(int flag,int maxLen,int len2 )
{
    if(flag==0 || maxLen==0){
        return;
    }
    for(int i = flag-maxLen; i < flag; i++){
        cout << s2[i];
    }
}

int main()
{
    cout<<"输入第一个字符串"<<endl;
    cin>>s1;
    cout<<"输入第二个字符串"<<endl;
    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;
    }
    LCSs();
    cout << "s1与s2的最长公共子序列的长度是:" << maxLen <<endl;
    cout << "s1与s2的最长公共子序列是:";
    PRINT(flag,maxLen,len2);
    return 0;
}