#include <stdio.h>
#include <string.h>
int GetNext(char *T, int *next)
{
int i = 0, j = -1;
next[i] = j;
while (i < strlen(T))
{
if (j == -1 || T[i] == T[j])
{
i++;
j++;
if (T[i] != T[j])
{
next[i] = j;
}
else
{
next[i] = next[j];
}
}
else
{
j = next[j];
}
}
}
int KMP(char *S, char *T, int *next)
{
int i = 0, j = 0;
GetNext(T, next);
while (i < strlen(S) && j < strlen(T))
{
if (j == -1 || S[i] == T[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j >= strlen(T))
{
return i - strlen(T);
}
else
{
return -1;
}
}