KMP改进后的算法基本没变,就是考虑到aaaaa这样的next为-1,0,1,2,3,4.
就是说通过next后原来的值可能当前值一样,改进后的算法作了一点小改动,使上面的next数组会变为-1,0,0,0,0,如果模式串有大量重复字符,可以提高效率
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define MaxSize 100
typedef struct {
char data[MaxSize];
int length;
}SqString;
//k表示的是前缀字符串的长度
void GetNextval(SqString *q, int *next)
{
int k = -1, j = 0;//k=-1;
next[0] = -1;
while (j < q->length-1)
{
if (k == -1||q->data[j]==q->data[k])
{
k++;j++;
if (q->data[j] == q->data[k])
{
next[j] = next[k];
}
else
{
next[j] = k;
}
}
else
{
k = next[k];
}
}
}
bool KMP(SqString s, SqString t)
{
int next[MaxSize],i = 0, j = 0;
GetNext(&t, next);
while (i < s.length && j < t.length)
{
if (j == -1 || s.data[i] == t.data[j])
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j == t.length)
{
return true;
}
else
{
return false;
}
}
int main()
{
SqString s = {{"abaam,hjbcabaabctrd"},19};
SqString t = { {"abaabc"},5 };
printf("%d", KMP(s, t));
return 0;
}
运行结果如下