用c++写出kmp算法代码
时间: 2023-04-08 17:04:02 浏览: 118
以下是KMP算法的C语言代码:
```c
#include <stdio.h>
#include <string.h>
void getNext(char *pattern, int *next) {
int i = 0, j = -1;
next[0] = -1;
while (i < strlen(pattern)) {
if (j == -1 || pattern[i] == pattern[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
int kmp(char *text, char *pattern) {
int i = 0, j = 0;
int next[strlen(pattern)];
getNext(pattern, next);
while (i < strlen(text) && j < strlen(pattern)) {
if (j == -1 || text[i] == pattern[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == strlen(pattern)) {
return i - j;
} else {
return -1;
}
}
int main() {
char text[] = "ABABABABCABAAB";
char pattern[] = "ABABCABAA";
int pos = kmp(text, pattern);
if (pos == -1) {
printf("Pattern not found in text\n");
} else {
printf("Pattern found at position %d in text\n", pos);
}
return 0;
}
```
注意:以上代码是我根据KMP算法的原理编写的,可能存在错误或不完善之处,仅供参考。
阅读全文