-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkmp.cc
56 lines (53 loc) · 1.07 KB
/
kmp.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <string.h>
#include <stdio.h>
#define MAXLEN 100
int Next[MAXLEN] = {0};
void Show(int * array, int len) {
for (int i = 0; i < len; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}
void ComputeNext(const char* P) {
size_t m = strlen(P + 1);
Next[1] = 0;
int k = 0;
for (int q = 2; q <=m; ++q) {
while (k > 0 && P[k+1] != P[q]) {
k = Next[k];
}
if (P[k+1] == P[q]) {
++k;
}
Next[q] = k;
}
Show(Next+1, m);
}
void KMP(const char* T, const char* P) {
size_t n = strlen(T + 1);
size_t m = strlen(P + 1);
ComputeNext(P);
int q = 0;
for (int i = 1; i <= n; ++i) {
while (q > 0 && P[q + 1] != T[i]) {
q = Next[q];
}
if (P[q + 1] == T[i]) {
++q;
}
if (q == m) {
printf("Match in pos %lu \n", i - m);
q = Next[q];
}
}
}
int main(int argc,char** argv) {
char T[MAXLEN] = {0};
char P[MAXLEN] = {0};
scanf("%s %s", T+1, P+1);
printf("%s %s\n", T+1, P+1);
printf("strlen(%s) :%lu, strlen(%s) : %lu\n",
T+1, strlen(T+1), P+1, strlen(P+1));
KMP(T, P);
return 0;
}