kmf算法c++实现
时间: 2023-11-25 14:51:23 浏览: 33
很抱歉,可能是因为您的输入有误,正确的算法应该是KMP算法,而不是kmf算法。以下是KMP算法的C++实现:
```c++
#include <iostream>
#include <cstring>
using namespace std;
void getNext(char* p, int* next) {
int len = strlen(p);
int j = 0, k = -1;
next[0] = -1;
while (j < len - 1) {
if (k == -1 || p[j] == p[k]) {
j++;
k++;
next[j] = k;
}
else {
k = next[k];
}
}
}
int KMP(char* s, char* p) {
int slen = strlen(s);
int plen = strlen(p);
int i = 0, j = 0;
int* next = new int[plen];
getNext(p, next);
while (i < slen && j < plen) {
if (j == -1 || s[i] == p[j]) {
i++;
j++;
}
else {
j = next[j];
}
}
delete[] next;
if (j == plen) {
return i - j;
}
else {
return -1;
}
}
int main() {
char s[100], p[100];
cin >> s >> p;
int pos = KMP(s, p);
if (pos == -1) {
cout << "Not Found" << endl;
}
else {
cout << "Found at position " << pos << endl;
}
return 0;
}
```