用C++写一个KMP算法
时间: 2023-12-27 08:48:34 浏览: 71
以下是C语言实现KMP算法的代码:
```c
#include <stdio.h>
#include <string.h>
void getNext(char* pattern, int* next) {
int len = strlen(pattern);
next[0] = -1;
int i = 0, j = -1;
while (i < len - 1) {
if (j == -1 || pattern[i] == pattern[j]) {
i++;
j++;
next[i] = j;
}
else {
j = next[j];
}
}
}
int kmp(char* text, char* pattern) {
int len1 = strlen(text);
int len2 = strlen(pattern);
int i = 0, j = 0;
int* next = (int*)malloc(len2 * sizeof(int));
getNext(pattern, next);
while (i < len1 && j < len2) {
if (j == -1 || text[i] == pattern[j]) {
i++;
j++;
}
else {
j = next[j];
}
}
free(next);
if (j == len2) {
return i - j;
}
else {
return -1;
}
}
int main() {
char* text = "hello world";
char* pattern = "world";
int index = kmp(text, pattern);
if (index != -1) {
printf("Pattern found at index %d\n", index);
}
else {
printf("Pattern not found\n");
}
return 0;
}
```
在上面的代码中,`getNext`函数用于计算模式串的`next`数组,`kmp`函数用于在文本串中匹配模式串。在`main`函数中,我们将文本串和模式串传入`kmp`函数,如果匹配成功则返回模式串在文本串中的起始位置,否则返回-1。
阅读全文