原理图示
代码
void get_next(char *Next, char *str)
{
Next[0] = -1; // 为什么首个元素赋值-1, 因为在求完next数组后实际匹配字符串过程中, 在找不到相同字符时,
// 需要继续从模串的首元素继续判断, 同时匹配失败时需要继续匹配下一个字符
int j = 0, k = -1, len = strlen(str);
while (j < len)
{
if (k == -1 || str[j] == str[k])
{
j++;
k++;
Next[j] = k; // 赋值
}
else
{
k = Next[k]; // 跳Next
}
}
}
/* 利用模式串p的next数组, 求p在主串s中第pos的字串开始的位置 */
/* 若匹配成功, 返回模式串在主串的位置(下标), 否则返回-1 */
int Index_KMP(char *s, char *p, int pos, int next[])
{
int i = pos -1;
int j = -1;
int slen = strlen(s);
int plen = strlen(p);
while (i < slen && j < plen) {
if (j == -1 || s[i] == p[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j >= plen) {
return i - plen;
} else {
return -1;
}
}
运行结果
-1 0 0 0 1 2 1 2 3 0