KMP算法是通过分析模式字符串,预先计算每个位置发生不匹配的时候,所需GOTO的下一个比较位置,整理出来一个next数组,然后在上面的算法中使用。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int next[255] = {0};
void getnext(char* s, int n)
{
int j = -1;
int i = 0;
/*赋初值*/
next[0] = -1;
while (i<n)
{
if (j==-1 || s[i]==s[j])
{
i++;
j++;
next[i] = j;
}
else
{
/*回溯*/
j = next[j];
}
}
}
/*KMP算法*/
bool strCmp(char *s, char *t)
{
int l = strlen(s);
int n = strlen(t);
int i = 0;
int j = -1;
getnext(t, n);
while (i<l && j<n)
{
if (j==-1 || s[i]==t[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (i == l)
{
return false;
}
else
{
return true;
}
}
int main()
{
char s[] = "aaacdege";
char t[] = "acee";
if (strCmp(s, t))
{
printf("TRUE\n");
}
else
{
printf("FALSE\n");
}
return 0;
}