数据结构实验之串一:KMP简单应用
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
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
Hint
#include <stdio.h>
#include <string.h>
char str[1000000],str1[1000000];
int next[1000000];
void getNext()//求子串的“部分匹配值”,就是前缀与后缀共有元的个数 详细描述见http://blog.csdn.net/hzq24601/article/details/55095061
{
int len = strlen(str1);
int i = 0,j = -1;
next[0] = -1;//十分巧妙的设计,j = -1, next[0] = -1 next数组存储部分匹配值
while(i<len){
if(j==-1||str1[i]==str1[j]){
i++;
j++;
next[i] = j;
}
else
j = next[j];
}
}
void kmp()
{
int i = 0,j = 0;
int str_len = strlen(str),str1_len = strlen(str1);
getNext();//有了next数组,发现匹配的就可以最小数量的移动串了
while(i<str_len&&j<str1_len){
if(j==-1||str[i]==str1[j]){
i++;
j++;
}
else
j = next[j];
}
if(j>=str1_len)
return i-j+1;//返回的是子串匹配主串的位置
else
return -1;
}
int main()
{
while(~scanf("%s%s",str,str1)){
printf("%d\n",kmp());
}
return 0;
}