-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathKMP.cpp
52 lines (51 loc) · 992 Bytes
/
KMP.cpp
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
#include <cstdio>
#include <string>
#include <string.h>
using namespace std;
int M, N;
char pat[1000000+10],txt[1000000+10];
int lps[1000000+10];
void builtFA(){
int i = 1;
int len = 0;
lps[0] = len = 0;
while( i < M){
if( pat[i] == pat[len]){
len++;
lps[i] = len;
i++;
}
else if(len == 0){
lps[i] = 0;
i++;
}
else{
len = lps[len-1];
}
}
}
void KMP(){
int k,i;
for( k = 0, i = 0; i < N; i++ ){
while( k && txt[i] != pat[k] )
k = lps[k-1];
if(txt[i] == pat[k]) k++;
if(k == M){
printf("%d ", i - M + 1);
k = lps[M-1];
}
}
puts("");
}
int main(){
#ifndef ONLINE_JUDGE
//freopen("input.txt", "r", stdin);
#endif
while(scanf("%d", &M) == 1){
scanf("%s %s", pat, txt);
N = strlen(txt);
builtFA();
KMP();
}
return 0;
}