#include<stdio.h>
#include<string.h>
void getNext(char T[],int *next)
{
int i = 1;
next[1] = 0;
int j = 0;
while (j < strlen(T))
{
if (j == 0 && T[i] == T[j])
{
++i;
++j;
next[i] = j;
}
else
{
j = next[j];
}
}
}
int KMP(char S[],char T[],int *next,int pos)
{
int i = pos;
int j = 1;
while (i<=strlen(S)&&j<=strlen(T))
{
if (j == 0 || S[i] == T[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if (j > strlen(T))
return i - strlen(T);
else
return 0;
}
void main()
{
int next[20];
int pos = 0;
printf_s("S= ");
char S[20];
gets_s(S, 20);
printf_s("\n");
printf_s("T= ");
char T[20];
gets_s(T, 20);
printf_s("\n");
getNext(T, next);
int index;
index = KMP(S,T,next,pos);
printf_s("%d ", index);
}