用C++写一个KMP算法
时间: 2023-05-27 21:02:42 浏览: 98
这是一个用C语言实现的KMP算法:
```c
#include <stdio.h>
#include <string.h>
void computeLPSArray(char* pat, int M, int* lps) {
int len = 0;
int i = 1;
lps[0] = 0;
while (i < M) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
}
else {
if (len != 0) {
len = lps[len-1];
}
else {
lps[i] = 0;
i++;
}
}
}
}
void KMP(char* pat, char* txt) {
int M = strlen(pat);
int N = strlen(txt);
int lps[M];
computeLPSArray(pat, M, lps);
int i = 0, j = 0;
while (i < N) {
if (pat[j] == txt[i]) {
j++;
i++;
}
if (j == M) {
printf("Found pattern at index %d\n", i-j);
j = lps[j-1];
}
else if (i < N && pat[j] != txt[i]) {
if (j != 0) {
j = lps[j-1];
}
else {
i++;
}
}
}
}
int main() {
char txt[] = "ABABDABACDABABCABAB";
char pat[] = "ABABCABAB";
printf("Text: %s\n", txt);
printf("Pattern: %s\n", pat);
KMP(pat, txt);
return 0;
}
```
输出:
```
Text: ABABDABACDABABCABAB
Pattern: ABABCABAB
Found pattern at index 10
```
阅读全文