最简单原始的KMP

nefu197:关键字检索

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

 

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 using namespace std;
 5 
 6 void get_next(char t[],int next[])
 7 {
 8     int j=-1,i=0;
 9     next[0]=-1;
10     while(i<strlen(t))
11     {
12         if(j==-1||t[i]==t[j])
13           {
14               i++,j++;
15               next[i]=j;
16           }
17         else
18           j=next[j];
19     }
20 }
21 int KMP(char s[],char t[])
22 {
23     int i=0,j=0;
24     int next[15];
25     get_next(t,next);
26     int len1=strlen(t);
27     int len2=strlen(s);
28     while(j<len1&&i<len2)
29     {
30         if(j==-1||t[j]==s[i])
31           i++,j++;
32         else
33           j=next[j];
34     }
35     if(j>=len1)
36       return 1;
37     else
38       return 0;
39 }
40 
41 int main()
42 {
43     char s[100005],t[15];
44     int n;
45     while(scanf("%d",&n)!=EOF)
46     {
47         for(int i=1;i<=n;i++)
48         {
49             scanf("%s%s",s,t);
50 
51             if(KMP(s,t)==1)
52               printf("Case #%d: Yes\n",i);
53             else
54               printf("Case #%d: No\n",i);
55         }
56     }
57     //cout << "Hello world!" << endl;
58     return 0;
59 }

 

posted on 2013-01-12 20:11  行者1992  阅读(193)  评论(0编辑  收藏  举报