http://blog.csdn.net/v_july_v/article/details/7041827
从头到尾彻底理解KMP(此博文甚好)
#include<iostream>
using namespace std;//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
void func(char *p,int *next)
{
int j=0;
int k=-1;
next[0]=-1;
while(j <strlen(p)-1)
if(k==-1||p[j]==p[k]) //匹配的情况下,p[j]==p[k]
{
++j;
++k;
if(p[j]==p[k]) //若p[j]==p[k],则需要修正
next[j]=next[k];
else
next[j]=k;
}
else //p[j]!=p[k]
k=next[k];
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
void func(char *p,int *next)
{
next[0]=-1;
next[1]=0;
for(int i=2;i<strlen(p);i++)
{
for(int j=i-1;j>0;j--)
{
if(equals(p,i,j))
{
next[i]=j; //找到最大的k值
break;
}
}
if(j==0)
next[i]=0;
}
}
bool equals(char *p,int i,int j) //判断p[0...j-1]与p[i-j...i-1]是否相等
{
int k=0;
int s=i-j;
for(;k<=j-1&&s<=i-1;k++,s++)
{
if(p[k]!=p[s])
return false;
}
return true;
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
int kmp(char s[],char t[],int next[])
{
int i=0,j=0;
while(s[i]!='\0'&&t[j]!='\0')
{
if(s[i]==t[j]){i++;j++;}
else j=next[j];
if(j==-1){i++;j++;}
}
if(t[j]=='\0')
return i-j+1;
else return 0;
}
int main()
{
char s[]="agajhfjhasgtjfghfjag";
char t[]="jf";
int next[10];
func(t,next);
cout<<kmp(s,t,next)<<endl;
return 0;
}