-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.cpp
More file actions
47 lines (43 loc) · 698 Bytes
/
KMP.cpp
File metadata and controls
47 lines (43 loc) · 698 Bytes
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
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define SZ 1000005
int pi[SZ];
char T[SZ], P[SZ];
int tsize, psize;
void compute_prefix_function(){
int k = -1;
int i = 1;
pi[0] = k;
for (i = 1; i < psize; i++) {
while (k > -1 && P[k+1] != P[i])
k = pi[k];
if (P[i] == P[k+1])
k++;
pi[i] = k;
}
}
void kmp(){
int i;
int k = -1;
compute_prefix_function();
for (i = 0; i < tsize; i++) {
while (k > -1 && P[k+1] != T[i])
k = pi[k];
if (T[i] == P[k+1])
k++;
if (k == psize - 1) {
printf("Pattern found at %d\n", i-k);
k = pi[k];
}
}
}
int main(){
gets(T);
gets(P);
tsize = strlen(T);
psize = strlen(P);
kmp();
return 0;
}