題目描述
輸入
輸出
示例輸入
abc a 123456 45 abc ddd
示例輸出
1 4 -1
///這個也是簡單的KMP算法,和學密碼一定要學程序一樣的意思,不過這個題目中有一句話是保證兩個字符串不出現空格,所以這個輸入字符串的時候應該用scanf("%s",s1);
而不能用gets(s1);如果用gets的話會一直WA;
#include<stdio.h>
#include<string.h>
#define N 1000001
char s1[N],s2[N];
int next[N];
void getnext()
{
int i=0,j=-1;
next[0]=-1;
while(s2[i]!='\0')
{
if(j==-1 || s2[i]==s2[j])
{
i++;
j++;
next[i]=j;
}
else
j=next[j];
}
}
void KMP()
{
int i=0,j=0;
getnext();
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)
{
printf("%d\n",i-len2+1);
}
else
{
printf("-1\n");
}
}
int main()
{
while(~scanf("%s",s1))
{
scanf("%s",s2);
KMP();
}
return 0;
}