SDUT 2772 数据结构实验之串一:KMP简单应用
数据结构实验之串一:KMP简单应用
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
给定两个字符串string1和string2,判断string2是否为string1的子串。
Input
输入包含多组数据,每组测试数据包含两行,第一行代表string1(长度小于1000000),第二行代表string2(长度小于1000000),string1和string2中保证不出现空格。
Output
对于每组输入数据,若string2是string1的子串,则输出string2在string1中的位置,若不是,输出-1。
Sample Input
abc a 123456 45 abc ddd
Sample Output
1 4 -1
提示:本题可以不用KMP算法,可以用一个比较舒服的strstr函数找到第一个子串在原字符串中的位置,
下面我将给出两种做法,当然用KMP是最快最省时间的,但是他麻烦呀,所以以后碰到这种题strstr基
本上也可以解决KMP可以解决的,除非他卡时间。
strstr函数实现(g++):
#include<bits/stdc++.h> using namespace std; char a[1000010]; char b[1000010]; int main() { while(scanf("%s %s",a,b)!=EOF) { char *ch=strstr(a,b);; if(ch=='\0') cout<<"-1"<<endl; else cout<<ch-a+1<<endl; } return 0; } /*************************************************** Result: Accepted Take time: 148ms Take Memory: 1264KB ****************************************************/
KMP函数实现(g++):
#include<bits/stdc++.h> using namespace std; char s1[1000010], s2[1000010]; int next[1000010]; void getnext() { int len = strlen(s2); int i = 0, j = -1; next[0] = -1; while(i < len) { if(j == -1 || s2[i] == s2[j]) { i++; j++; if(s2[i] != s2[j]) next[i] = j; else next[i] = next[j]; } else j = next[j]; } } int kmp() { int i = 0, j = 0; int len1 = strlen(s1); int len2 = strlen(s2); while(i < len1 && j < len2) { if(j == -1 || s1[i] == s2[j]) { i++; j++; } else { j = next[j]; } } if(j >= len2) { return i-j+1; } else return -1; } int main() { while(~scanf("%s", s1)) { scanf("%s", s2); getnext(); printf("%d\n", kmp()); } return 0; } /*************************************************** Result: Accepted Take time: 100ms Take Memory: 1252KB ****************************************************/
由以上两种代码可以看出KMP是非常快的(虽然它打得多,关于KMP我会在之后讲到。

浙公网安备 33010602011771号