#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void getNext(char T[], int next[])
{
int i = 0;
int j = -1;
next[0] = -1;
while (i < strlen(T))
{
if (j==-1||T[i] == T[j])
{
i++;
j++;
next[i] = j;
}
else
{
if (j == 0)
i++;
else
j = next[j];
}
}
}
int KMP(char S[], char T[])
{
int i = 0,j=0;
int lens = strlen(S);
int lent = strlen(T);
int next[100] = { 0 };
getNext(T, next);
while (i < lens&&j < lent)
{
if (j == -1 || S[i] == T[j])
{
i++;
j++;
}
else
j = next[j];
}
if (j == lent)
return(i - j);
else
return -1;
}
int main()
{
char S[] = "abcde";
char T[] = "e";
printf("%d", KMP(S, T));
}
08-20
395
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-24
242
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-20
249
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)