KMP(http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2772)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char a[1000001],b[1000001];
int next[1000001];
int l,l2;
void Getnext()
{
int i=0;
int j=-1;
next[0]=-1;
while(i<l2)
{
if(-1==j||b[i]==b[j])
{
i++;
j++;
next[i]=j;
}
else j=next[j];
}
}
int main()
{

while(scanf("%s",a)!=EOF)
{
scanf("%*c%s",b);
l=strlen(a);
l2=strlen(b);
Getnext();
int i=0;
int j=0;
while(i<l&&j<l2)
{
if(a[i]==b[j]||j==-1)
{
i++;
j++;

}
else j=next[j];
}
if(j>=l2) printf("%d ",i-l2+1);//判断条件
else printf("-1 ");
}
return 0;
}

原文地址:https://www.cnblogs.com/zhangmingcheng/p/3793326.html