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
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int next[10005];
char str1[1000005],str2[10005];
int n;

void get_next(int len2)//生成next数组
{
    int i = 0,j = -1;
    next[0] = -1;
    while (i<len2)
    {
        if(j == -1 || str2[i] == str2[j])
        {
            i++;
            j++;
            if (str2[i]!=str2[j])
                next[i] = j;
            else
                next[i] = next[j];
        }
        else
            j = next[j];
    }
}

int kmp(int len1,int len2)
{
    int i=0,j=0;
    get_next(len2);
    while(i<len1)
    {
        if(j==-1||str1[i]==str2[j])
        {
            i++;j++;
        }
        else
        j=next[j];
        if(j==len2)
        {
            return 1;
        }
    }
}

int main()
{
    int kase=1,k;
    cin>>n;
    getchar();
    while(n--)
    {
        k=0;
        cin>>str1>>str2;
        get_next(strlen(str2));
        k=kmp(strlen(str1),strlen(str2));
        if(k==1)
        printf("Case #%d: Yes\n",kase);
        else
        printf("Case #%d: No\n",kase);
        kase++;
    }
    return 0;
}

 

posted @ 2016-03-15 21:08  邻家那小孩儿  阅读(270)  评论(0编辑  收藏  举报