最长公共子序列

#include <bits/stdc++.h>

using namespace std;

int Length[66][66];
int Way[66][66];//用来判断输出
char s[50];
char t[50];

int LCS_length(int ls,int lt)
{
    for(int i=0;i<=ls;i++)
    {
        Length[i][0]=0;
    }
    for(int j=0;j<=lt;j++)
    {
        Length[0][j]=0;
    }
    for(int x=1;x<=ls;x++)
    {
        for(int y=1;y<=lt;y++)
        {
            if(s[x-1]==t[y-1])
            {
                Length[x][y]=Length[x-1][y-1]+1;
                Way[x][y]=1;
            }
            else if(Length[x-1][y]>=Length[x][y-1])
            {
                Length[x][y]=Length[x-1][y];
                Way[x][y]=2;
            }
            else
            {
                Length[x][y]=Length[x][y-1];
                Way[x][y]=3;
            }
        }
    }
    return Length[ls][lt];
}

void Cout_LCS(int ls,int lt)
{
    if(ls==0||lt==0)
    {
        return ;
    }
    if(Way[ls][lt]==1)
    {
        Cout_LCS(ls-1,lt-1);
        cout<<s[ls-1];
    }
    else if(Way[ls][lt]==2)
    {
        Cout_LCS(ls-1,lt);
    }
    else if(Way[ls][lt]==3)
    {
        Cout_LCS(ls,lt-1);
    }
}

int main()
{
    cin>>s;
    cin>>t;
    int ls=strlen(s);
    int lt=strlen(t);
    cout<<LCS_length(ls,lt);
    Cout_LCS(ls,lt);
    return 0;
}
 

 

 

#include <bits/stdc++.h>

using namespace std;

int b[55];//记录长度
int d[55];
void Lengthest_Son_Public_Str(char *s,char *t)//只需要两个字符串
{
    int m=strlen(s);
    int n=strlen(t);
    for(int i=0;i<=n;i++)
    {
        b[i]=0;
        d[i]=0;
    }
    for(int r=1;r<=m;r++)
    {
        for(int c=1;c<=n;c++)
        {
            if(s[r-1]==t[c-1])
            {
                d[c]=b[c-1]+1;
                cout<<d[c];
            }
            else if(d[c-1]>=b[c])
            {
                d[c]=d[c-1];
                cout<<d[c];
            }
            else
            {
                d[c]=b[c];
                cout<<d[c];
            }
        }
        cout<<endl;
        memcpy(b,d,sizeof(d));
        memset(d,0,sizeof(d));
    }
}

int main()
{
    char s[50],t[21];
    cin>>s;
    cin>>t;
    int ls=strlen(s);
    int lt=strlen(t);
    Lengthest_Son_Public_Str(s,t);
    for(int i=0;i<=lt;i++)
    {
        cout<<' '<<b[i];
    }
    return 0;
}
/*
abcbdb
acbbabdbb
*/
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值