KMP模式匹配改进版
#include<iostream>
#include<string>
using namespace std;
void get_nextval(string T,int * nextval)
{
int i,j;
i=0;
j=-1;
nextval[0]=-1;
int lenT=T.length();
while(i<lenT)
{
if(j==-1 || T[i]==T[j])
{
++i;
++j;
if(T[i]!=T[j])
{
nextval[i]=j;
}
else
{
nextval[i]=nextval[j];
}
}
else
{
j=nextval[j];
}
}
}
/*返回子串T在主串S中第pos个字符之后的位置。若不存在,则函数返回-1*/
int index_KMP(string S,string T,int pos)
{
int i=pos;
int j=0;
int lenS=S.length();
int lenT=T.length();
int nextval[255];
get_nextval(T,nextval);
while(i<lenS && j<lenT)
{
if(j==0 || S[i]==T[j])
{
++i;
++j;
}
else
{
j=nextval[j];
}
}
if(j>=lenT)
{
return i-lenT;
}
else
{
return -1;
}
}