SDUT 2772 数据结构实验之串一:KMP简单应用

数据结构实验之串一:KMP简单应用

Time Limit: 1000MS Memory Limit: 65536KB

Problem Description

给定两个字符串string1和string2,判断string2是否为string1的子串。

Input

 输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。

Output

 对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。

Example Input

abc
a
123456
45
abc
ddd

Example Output

1
4
-1

DQE:

 
KMP算法的经典应用,可自己推算一下或查阅相关资料。
 
 1 #include <iostream>
 2 #include <cstdio>
 3 
 4 using namespace std;
 5 
 6 int strlen(char *s)
 7 {
 8     int i=0;
 9     while(s[i]!='\0')
10     {
11         i++;
12     }
13     return i;
14 }
15 
16 void cnext(char *s,int *next)
17 {
18     int l=strlen(s);
19     int i=0,j=-1;
20     next[i]=j;
21     while(i<l-1)
22     {
23         if(j==-1||s[i]==s[j])
24         {
25             i++;
26             j++;
27             next[i]=j;
28         }
29         else
30         {
31             j=next[j];
32         }
33     }
34 }
35 
36 int kmp(char *s1,char *s2,int *next)
37 {
38     int l1=strlen(s1),l2=strlen(s2);
39     int i=0,j=0;
40     while(i<l1&&j<l2)
41     {
42         if(j==-1||s1[i]==s2[j])
43         {
44             i++;
45             j++;
46         }
47         else
48         {
49             j=next[j];
50         }
51     }
52     if(j>=l2)
53         return i-l2+1;
54     return -1;
55 }
56 
57 int main()
58 {
59     static char s1[1000010],s2[1000010];
60     static int next[1000010];    //此处用static不完全等同于放到全局变量
61     while(gets(s1))
62     {
63         gets(s2);
64         cnext(s2,next);
65         printf("%d\n",kmp(s1,s2,next));
66     }
67     return 0;
68 }
69 
70 /***************************************************
71 User name: ***
72 Result: Accepted
73 Take time: 68ms
74 Take Memory: 1012KB
75 Submit time: 2016-11-02 21:33:59
76 ****************************************************/

 

posted @ 2016-11-04 22:30  Leroscox  阅读(423)  评论(0编辑  收藏  举报