nefu 197 KMP

Posted a_clown_cz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nefu 197 KMP相关的知识,希望对你有一定的参考价值。

Description

在信息检索系统中一个很重要的环节就是关键字符串的查找,从而很多对自己有用的信息。给你一个很长的一段文字, 和一个关键信息字符串,现在要你判断这段文字里面是否有关键字符串。

Input

输入数据有多行,第一行是一个整数n,表示测试实例的个数,后面跟着n行,每行包括一段文字(中间不含空格,长度不超过1000),和一个关键信息字符串(长度不超过10)

Output

输出这段文字里面是否有关键字符串,如果有则输出Yes,否者输入No,具体细节见样例。

Sample Input

3
songpanda  pan
hudzpdgj  huz
aabdcc  ad

Sample Output

Case #1: Yes
Case #2: No
Case #3: No

KMP:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
char str1[1005],str2[1005];
int next[1005];
void getnext(int L)
{
    int i=0,j=-1;
    next[0]=-1;
    while(i<L)
    {
        if(j==-1 || str2[j]==str2[i])
        {
            i++;
            j++;
            if(str2[i]!=str2[j]) next[i]=j;
            else next[i]=next[j];
        }
        else j=next[j];
    }
}
int kmp(int L1,int L2)
{
    getnext(L2);
    int i=0,j=0;
    while(i<L1)
    {
        if(j==-1 || str1[i]==str2[j]) i++,j++;
        else j=next[j];
        if(j==L2) return 1;
    }
    return 0;
}
int main()
{
    int n;
    int k=0;
    scanf("%d",&n);
    getchar();
    while(n--)
    {
        scanf("%s%s",str1,str2);
        int ans=kmp(strlen(str1),strlen(str2));
        if(ans==1) printf("Case #%d: Yes\n",++k);
        else  printf("Case #%d: No\n",++k);
    }
    return 0;
}

 

以上是关于nefu 197 KMP的主要内容,如果未能解决你的问题,请参考以下文章

[NEFU算法设计与分析] 代码汇总

NEFU大一下C语言阶段一考试参考代码(带注释)

[NEFU 数据结构]阶段二复习

BZOJ4641基因改造 KMP

[NEFU 数据结构] 第 1 章 绪论 知识点整理

[NEFU 数据结构] 第 2 章 线性表 知识点整理