如何用c语言写一个kmp算法
时间: 2023-04-04 19:02:54 浏览: 109
可以使用以下代码实现KMP算法:
#include <stdio.h>
#include <string.h>
void getNext(char *p, int *next) {
int len = strlen(p);
int i = 0, j = -1;
next[0] = -1;
while (i < len) {
if (j == -1 || p[i] == p[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
int kmp(char *s, char *p) {
int slen = strlen(s);
int plen = strlen(p);
int i = 0, j = 0;
int next[plen];
getNext(p, next);
while (i < slen && j < plen) {
if (j == -1 || s[i] == p[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == plen) {
return i - j;
} else {
return -1;
}
}
int main() {
char s[] = "ababcabcacbab";
char p[] = "abcac";
int pos = kmp(s, p);
printf("%d\n", pos);
return 0;
}
阅读全文