kmp算法代码实现c
时间: 2023-11-19 21:57:16 浏览: 101
kmp算法的实现.doc
以下是KMP算法的C语言实现代码,其中包括了求解next数组的函数和KMP算法的主函数:
```c
#include <stdio.h>
#include <string.h>
void getNext(char *P, int *next) {
int pLen = strlen(P);
next[0] = -1;
int k = -1;
int j = 0;
while (j < pLen - 1) {
if (k == -1 || P[j] == P[k]) {
++j;
++k;
if (P[j] != P[k]) {
next[j] = k;
} else {
next[j] = next[k];
}
} else {
k = next[k];
}
}
}
void KMP(char *T, char *P, int *next) {
int tLen = strlen(T);
int pLen = strlen(P);
int i = 0;
int j = 0;
while (i < tLen && j < pLen) {
if (j == -1 || T[i] == P[j]) {
++i;
++j;
} else {
j = next[j];
}
}
if (j == pLen) {
printf("Pattern found at index %d\n", i - j);
} else {
printf("Pattern not found\n");
}
}
int main() {
char T[] = "ABABDABACDABABCABAB";
char P[] = "ABABCABAB";
int next[strlen(P)];
getNext(P, next);
KMP(T, P, next);
return 0;
}
```
阅读全文