
int* Get_Next(const char* sub)
{
assert(NULL != sub);
int len = strlen(sub);
int* next = (int*)malloc(len * sizeof(int));
if (NULL == next)exit(1);
//1.前两个格子给-1 0
next[0] = -1;
next[1] = 0;
//2.通过已知推未知
int j = 1;//j表示next数组的下标
int k = next[1];//保存当前的回退位置,k在变化
while (j + 1 < len)
{
if (k==-1||sub[j] == sub[k])
{
k++;
j++;
next[j] = k;
}
else
{
k = next[k];
}
}
return next;
}
int KMP_Maching(const char* str, const char* sub)
{
assert(str != NULL);
assert(sub != NULL);
int i = 0;
int j = 0;
int len_str = strlen(str);
int len_sub = strlen(sub);
int* next = Get_Next(sub);
while (i <len_str && j < len_sub)
{
if (j==-1||str[i] == sub[j])
{
i++;
j++;
}
else
{
//让j回退到合适的位置,从而让i可以不用回退
j = next[j];
}
}
if (j > strlen(sub))
{
return -1;
}
free(next);
return i - j;
}

int* Get_NextVal(const char* sub)
{
int* next = Get_Next(sub);
int len = strlen(sub);
int* nextval = (int*)malloc(len * sizeof(int));
if (NULL == nextval)exit(1);
nextval[0] = -1;
for (int i = 1; i < len; i++)
{
if (sub[i] == sub[next[i]])
{
nextval[i] = next[i];
}
else
{
nextval[i] = nextval[next[i]];
}
}
free(next);
return nextval;
}