#include <iostream>
#include <cstring>
using namespace std;
#define MAXLEN 255
typedef struct {
char ch[MAXLEN+1]; // 0号位置不存储字符
int length;
}SString;
int n[100];
bool initSString(SString &s, char *str) {
int len = strlen(str);
for (int i = 0; i < len; ++i) {
s.ch[i+1] = str[i];
}
s.length = len;
return true;
}
int index_KMP(SString s, SString t, int pos) {
int i = pos, j = 1;
while (i <= s.length && j <= t.length) {
if (j == 0 || s.ch[i] == t.ch[j]) {
i++;
j++;
} else {
j = n[j];
}
}
if (j > t.length) {
return i - t.length;
} else {
return 0;
}
}
void get_next(SString t, int next[]) {
int i = 1;
next[1] = 0;
int j = 0;
while (i < t.length) {
if (j == 0 || t.ch[i] == t.ch[j]) {
i++;
j++;
if (t.ch[i] != t.ch[j]) {
next[i] = j;
} else {
next[i] = next[j];
}
} else {
j = next[j];
}
}
}
int main() {
SString s, t;
char str[MAXLEN];
cin >> str;
initSString(s, str);
cin >> str;
initSString(t, str);
get_next(t, n);
int ans = index_KMP(s, t, 1);
if (ans) {
cout << "匹配的位置是 : " << ans << endl;
}
return 0;
}
[数据结构]--模式匹配KMP算法
最新推荐文章于 2022-10-17 22:18:24 发布