KMP算法求解的是字串匹配的算法
例如 求出“abcbadd”中 ""
#include<iostream>
using namespace std;
void get_next(char * substr, int *next)
{
int i=1,j=0;
next[1]=0;
while(i<substr[0])
{
if(0==j||substr[i]==substr[j])
{
++j;
++i;
if(substr[i]!=substr[j])
next[i]=j;
else
next[i]=next[j];
}
else
j = next[j];
}
}
int Index(char *f,char * subt)
{
int i = 1;
int j = 1;
int next[255];
get_next(subt,next);
while(i<=f[0] && j <=subt[0])
{
if(0==j||f[i]==subt[j])
{
++i;
++j;
}
else
{
j=next[j];
}
}
if(j>subt[0])
return i - subt[0];
return 0;
}
int main()
{
char f[13]={12,'a','b','c','d','e','a','c','d','d','e','a','b',};
char sub[5]={4,'a','c','d','d'};
cout<<Index(f,sub);
return 0;
}