void computeNext(string pat, int patLenth, int* next) {
int len = 0;
int i = 1;
next[0] = 0;
//pat[i] 与 pat[len] 比
// i 1 2 3 4 5 6 7 8 9
//pat a b c d a b c a b a
//next 0 0 0 0 1 2 3 1 2 1
//len 0 1 2 3 0 1 2 0 1
while (i < patLenth) {
//pat从1开始遍历,与pat[len]相等否?
if (pat[i] == pat[len]) { //相等
len++; //len自加
next[i] = len; //next[i]与len同
i++; //i往后遍历
}
else { //不等
if (len != 0) { //且len不为0
len = next[len - 1]; //len改值为next的第len个数 重新比较
}
else { //且len为0
next[i] = 0; //next[i]赋值为0
i++; //i往后遍历
}
}
}
}
void KMPSearch(string pat, string txt) {
int patLenth = pat.length();
int txtLenth = txt.length();
int* next = (int*)malloc(patLenth * sizeof(int));
int j = 0; // index for pat[]
computeNext(pat, patLenth, next);
int i = 0; // index for txt[]
while (i < txtLenth) {
if (pat[j] == txt[i]) {
j++;
i++;
}
if (j == patLenth) {
printf("Found pattern at index %d \n", i - j);
j = next[j - 1];
break;
}
else if (i < txtLenth && pat[j] != txt[i]) {
if (j != 0)//后面的不匹配
j = next[j - 1]; // j 从 next数组的第j个对应的数重新开始
else//第一个不匹配
i = i + 1; // txt往后遍历
}
}
free(next);
}
C语言实现KMP
于 2024-04-30 17:04:42 首次发布
607






