#include <stdio.h>
typedef char* String;
void getnext(String T, int *next)
{
j=0, i=1;
next[1] = 0;
while ( i < T[0])
{
if ( j==0||T[i]==T[j])
{
i++;
j++;
if ( T[i] != T[j])
{
next[i] = j;
}
else //改进后
{
next[i] = next[j];
}
}
else
{
//j回溯
j = next[j];
}
}
}
//返回子串T在主串S第pos个字符之后的位置
// 若不存在,则返回0
int Index_KMP(String S, String T, int pos)
{
int i = pos;
int j = 1;
int next[255];
getnext (T, next);
while (i <= S[0] && j<=T[0] )
{
if (S[i] == T[j] || j==0)
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j > T[0])
{
return i - T[0];
}
else
{
return 0;
}
}