2021-10-15

最长匹配问题

题目描述
A newly opened detective agency is struggling with their limited intelligence to find out a secret information passing technique among its detectives. Since they are new in this profession, they know well that their messages will easily be trapped and hence modified by other groups. They want to guess the intensions of other groups by checking the changed sections of messages. First they have to get the length of longest match. You are going to
help them.
输入
The input file may contain multiple test cases. Each case will contain two successive lines of string. Blank lines and non-letter printable punctuation characters may appear. Each Line of string will be no longer than 1000 characters. Length of each word will be less than 20 characters.
输出
For each case of input, you have to output a line starting with the case no right justified in a field width of two, followed by the longest match as shown in the sample output. In case of at least one blank line for each input output ‘Blank!’. Consider the non-letter punctuation characters as white-spaces.
题目大意:对于输入的一组数据,要找到最长的公共单词长度,只要将单词转化为字母就可以把此问题转化为最长公共子序列的问题,所以本问题重点在于如何对单词进行转化。
首先对每个单词提取出首字母,然后先对句子中短单词个数进行处理(好比late-breaking分成两个单词),然后再对单词个数进行一次排查(防止出现“,,”“-,”这样的连续字符出现在句子里影响对单词个数的判断)

#include <cstdio>
#include <string.h>
#include <string>
#include <iostream>
using namespace std;
int f[1010][1010];
struct node 
{
    int num;
    string word[1010];
};
 
void spa(string s,node &t)
{
    int len=s.length();
    t.num=1;
    for(int i=0;i<len;i++)
    {
        if((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z')||(s[i]>='0'&&s[i]<='9'))
        t.word[t.num]+=s[i];
        else
        t.num++;//所得num即为单词个数 
    }
    int n=0;
    for(int i=1;i<=t.num;i++) 
     {
        if(!t.word[i].empty())
        t.word[++n]=t.word[i];
     }
     t.num=n;
}
int main()
{
    int pp=1;
    string x,y;
    node t1,t2;
    while(!cin.eof())
    {
        string x,y;
        node t1,t2;
        getline(cin,x);
        spa(x,t1);
        getline(cin,y);
        spa(y,t2);
        printf("%2d. ",pp++);
        if(x.empty()||y.empty())
        {
            printf("Blank!\n");
            continue;
        }
        memset(f,0,sizeof(f));
        for(int i=1;i<=t1.num;i++)
        {
            for(int j=1;j<=t2.num;j++)
            {
                if(t1.word[i]==t2.word[j])
                f[i][j]=max(f[i-1][j-1]+1,f[i][j]);
                else
                f[i][j]=max(f[i-1][j],f[i][j-1]);
            }
        }
        printf("Length of longest match: %d\n",f[t1.num][t2.num]);
    }
    return 0;
}

empty()函数用于判断容器是否为空
(判断变量是否定义且不为NULL,’’,0,false)
当容器为空返回true
当容器不为空返回false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值