KMP算法(模式匹配算法)
KMP算法利用部分匹配结果避免指针回溯,具体是next数组或者改良后的nextval数组实现;
next的实现利用递推的思想,比较抽象,不容易理解。
include <stdio.h>
#include <string>
void Get_Next(char* str, int* next)
{
int len = strlen(str);
int i = 0, j = -1; next[0] = -1;
while (i < len)
{
if (j == -1 || str[i] == str[j]) {
j++; i++; next[i] = j;
}
else j = next[j];
}
}
void Get_NextVal(char* str, int* nextval)
{
int len = strlen(str);
int i = 0, j = -1;
nextval[0] = -1;
while (i < len)
{
if (j == -1 || str[i] == str[j])
{
i++; j++;
if (str[i] == str[j]) nextval[i] = nextval[j];
else nextval[i] = j;
}
else j = nextval[j];
}
}
int Index_KMP(char* Str1, char* Str2,int* next)
{
int i = 0, j = 0;
int len1 = strlen(Str1), len2 = strlen(Str2);
while (i < len1 && j < len2)
{
if (j == -1 || Str1[i] == Str2[j])
{
i++; j++;
}
else j = next[j];
}
if (j >= len2) return i - len2;
else return 0;
}
int main()
{
char str[] = "ababcabcacbab";
char Str[] = "abcac";
int len = strlen(Str);
int* next = (int*)malloc(sizeof(int) * len);
Get_Next(Str, next);
int* nextval = (int*)malloc(sizeof(int) * len);
Get_NextVal(Str, nextval);
printf("%d\n", Index_KMP(str,Str,nextval));
}

浙公网安备 33010602011771号