KMP算法
1.主串的i不回退
2.字串的j不会每次回退到字串开始处
int KMP(char* str, char* sub, int pos)
{
assert(str && sub);
int StrLen = strlen(str);
int SubLen = strlen(sub);
assert(StrLen >= SubLen);
assert(pos >= 0 && pos < StrLen);
int* next = (int*)malloc(sizeof(int) * SubLen);
GetNext(sub, SubLen, next);
int* nextval = (int*)malloc(sizeof(int) * SubLen);
GetNextVal(sub, SubLen, next, nextval);
int i = pos;
int j = 0;
while (i < StrLen)
{
if (j == -1 || str[i] == sub[j];
{
i++;
j++;
}
else
{
j = nextval[j];//回退到j要回退的位置,即该位置之前有两个相等字串,不需要比较
}
}
if (j >= SubLen)
return i - j;
return -1;
}
next数组
针对字串每次不回退到开始处,创建next原来保存j每次回退的位置。next数组的0下标值为-1,1下标值为0,固定不变。next值表示字串中,以0下标的字符为开头,以j-1下标为结尾的两个相等字串的长度,如果没有相等字串,next值为0。
1.next的值递增规律总是+1,每增加一个字符,相等字符串的字符数最多+1,但能直接减少为0
2.字串的最后一个字符不影响next数组的值。
void GetNext(char* sub, int SubLen, int* next)
{
next[0] = -1;
next[1] = 0;
int i = 2;
int k = 0;//k为sub[i-1]的next值,前一项要回退到的下标
while (i < SubLen)
{
if (k == -1 || sub[i -1] =sub[k])
{
next[i] = k + 1;
i++;
k++;
}
else
{
k = next[k];
}
}
}
nextval
当遇到一个字符发生回退时,如果回退的字符与回退之前的字符一样,则该字符的nextval值保存为回退字符的next值。如果不相同则保存.
回退的字符与没回退之前一样,回退便无意义,所以要回退到与没回退之前的字符不一样的字符处。
void GetNextVal(char* sub, int SubLen, int* next, int* nextval)
{
nextval[0] = -1;
for (int i = 1; i < SubLen; i++)
{
if (sub[i] == sub[next[i]])
nextval[i] = next[next[i]];
else
nextval[i] = next[i];
}
}