【C++】子序列匹配问题

复制代码
/*
一个串的“子序列”(subsequence)是将这个串中的一些字符提取出来得到一个新串,并且不改变它们的相对位置关系。例如,串"XDoi","XianYu!","TaiQiangLa!","loa"都是串"XianYuDalaoTaiQiangLa!"的子序列。

我们说串t是串s1和s2的公共子序列,当且仅当t是s1的子序列且t是s2的子序列。定义串s1和s2的相似度为它们最长公共子序列的长度。

现在给定一个文本串S和一组模式串T[1]、T[2]、……、T[n]。求T[i]中和S具有最高相似度的那个,然后输出最高的相似度。S和所有的T[i]都只含有小写字母。

输入规则:先是一行字符串S。第二行是n(1<=n<=100)。第三行以降的n行是n个模式串T[1]...T[n]。S和所有的T[i]的长度都不超过2000.

Sample Input:
abcdef

4

acfaff

appont

emmm

bdxeuf

Sample Output:
bdxeuf

4

Description:
串abcdef和bdxeuf的最长公共子序列是bdef,长度为4.
*/


#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int M=2010;

int result[100];

/*
void match(char *a,char *b,int s,int t,int i)
{
    int x=s;
    int y=t;
    while(a[x]!='\0')
    {
        while(b[y]!='\0')
        {
            if(a[x]==b[y])
            {
                result[i]++;
                match(a,b,x+1,y+1,i);
                cout<<b[y]<<endl;
            }
            y++;
        }
        x++;
    }
    
}
*/

void match(char *a,char *b,int s,int t,int i)
{
    int x=0;
    for(s=0;a[s]!='\0';s++)
    {
        for(t=x;b[t]!='\0';t++)
        {
            if(a[s]==b[t])
            {
                result[i]++;
                x++;
                //cout<<b[t]<<endl;
                break;
            }
        }
    }
}

/*
bool compare(int a,int b)//降序为> 
{
    return a>b;
}
*/
int main()
{
    char a[M];
    char b[100][M];
    memset(a,'\0',sizeof(a));
    int n;
    
    while(scanf("%s",&a))
    {
        memset(b,'\0',sizeof(b));
        memset(result,0,sizeof(result));
        cin>>n;
        for(int i=0;i<n;i++)
            scanf("%s",&b[i]);
        for(int i=0;i<n;i++)
        {
            match(a,b[i],0,0,i);
            //cout<<"result:"<<result[i]<<";"<<b[i]<<endl;
        }
        /*
        sort(result,result+n,compare);
        cout<<result[0]<<endl;
        memset(a,'\0',sizeof(a));
        */
        int max=result[0];
        int max_num=0;
        for(int i=1;i<n;i++)
        {
            if(result[i]>max)
            {
                max_num=i;
                max=result[i];
            }
        }
        cout<<b[max_num]<<endl<<max<<endl;
        memset(a,'\0',sizeof(a));
    }
    
    return 0;
}
复制代码

 代码运行说明:

 

 

tz@HZAU

2019/3/7

posted on   tuzhuo  阅读(1650)  评论(0编辑  收藏  举报

编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
历史上的今天:
2018-03-07 Android+Tomcat通过http获取本机服务器资源
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示