KMP分为两部分,一部分为匹配,一部分寻找next,
寻找next
void getNext( )
{
Next[0] = -1;
int i = 0, j = -1;
int len=strlen(p);
while (i < len)
{
if (j == -1 || p[i] == p[j])
{
++i;
++j;
Next[i] = j;
}
else
j = Next[j];
}
}
匹配
void KMP( )
{
int i = 0;
int j = 0;
int len1=strlen(t);
int len2=strlen(p);
while (i < len1 && j < len2)
{
if (j == -1 || t[i] == p[j])
{
i++;
j++;
}
else j = Next[j];
}
if (j == len2)
cout<<i-j+1<<endl;
else
cout<<"::>_<::"<<endl;
}