请用c++写出KMP算法下字符串匹配
时间: 2023-11-21 12:04:44 浏览: 89
好的,以下是使用C语言实现KMP算法进行字符串匹配的代码:
```c
#include <stdio.h>
#include <string.h>
void getNext(char *pattern, int next[]) {
int len = strlen(pattern);
next[0] = -1;
int i = -1, j = 0;
while (j < len - 1) {
if (i == -1 || pattern[i] == pattern[j]) {
i++;
j++;
next[j] = i;
} else {
i = next[i];
}
}
}
int KMP(char *text, char *pattern) {
int tlen = strlen(text);
int plen = strlen(pattern);
int next[plen];
getNext(pattern, next);
int i = 0, j = 0;
while (i < tlen && j < plen) {
if (j == -1 || text[i] == pattern[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == plen) {
return i - j;
} else {
return -1;
}
}
int main() {
char text[] = "ABABABCABAABABABAB";
char pattern[] = "ABABAB";
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;
}
```
希望这个代码能够帮到你。如果你有更多问题,可以继续问我。
阅读全文