帮我用C++写一个KMP
时间: 2023-03-26 12:01:03 浏览: 86
算法的代码。
好的,以下是 KMP 算法的 C 代码:
#include <stdio.h>
#include <string.h>
void kmp(char *text, char *pattern) {
int n = strlen(text);
int m = strlen(pattern);
int i = , j = ;
int *next = (int *)malloc(sizeof(int) * m);
get_next(pattern, next);
while (i < n) {
if (j == -1 || text[i] == pattern[j]) {
i++;
j++;
} else {
j = next[j];
}
if (j == m) {
printf("Pattern found at index %d\n", i - m);
j = next[j];
}
}
free(next);
}
void get_next(char *pattern, int *next) {
int m = strlen(pattern);
int i = , j = -1;
next[] = -1;
while (i < m) {
if (j == -1 || pattern[i] == pattern[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
int main() {
char text[] = "ABABDABACDABABCABAB";
char pattern[] = "ABABCABAB";
kmp(text, pattern);
return ;
}
阅读全文