#include <iostream>
using namespace std;
bool getNext(char T[], int length, int *next) {
int i = 1;
int j = 0;
next[i-1] = 0;
while(i < length) {
if(j == 0 || T[i-1] == T[j-1]) {
i ++;
j ++;
next[i-1] = j;
}
else {
j = next[j-1];
}
}
return true;
}
int KMP(char S[], int lengths, char T[], int lengtht) {
int *next;
next = new int[lengtht];
getNext(T, lengtht, next);
for(int i = 0; i < lengtht; i ++) {
cout << *(next + i) << " ";
}
cout << endl;
int i = 1;
int j = 1;
while(i <= lengths && j <= lengtht) {
if(j == 0 || S[i-1] == T[j-1]) {
i ++;
j ++;
}
else {
j = next[j-1];
}
}
if(j > lengtht) return i - lengtht;
else return -1;
}
int main() {
char S[] = "abagooglegg";
char T[] = "google";
int res = KMP(S, 11, T, 6);
cout << res;
cout << endl;
return 0;
}
数据结构KMP模式匹配C语言
最新推荐文章于 2025-01-18 00:17:35 发布
1048

被折叠的 条评论
为什么被折叠?



