-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathKMP.cpp
More file actions
48 lines (43 loc) · 745 Bytes
/
Copy pathKMP.cpp
File metadata and controls
48 lines (43 loc) · 745 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 <iostream>
#define MAX_N 100005
int reset[MAX_N];
using namespace std;
void KMPpreprocess(string pat) {
int i = 0, j = 1;
reset[0] = -1;
while(i < pat.size()) {
// Check for resetting
while(j >= 0 and pat[i]!=pat[j]) {
j = reset[j];
}
i++;
j++;
reset[i] = j;
}
}
void KMPsearch(string str, string pat) {
KMPpreprocess(pat);
int i = 0, j = 0;
while(i < str.size()) {
while(j >= 0 and str[i] != pat[j]) {
j = reset[j];
}
i++;
j++;
if(j == pat.size()) {
cout<<"Pattern is found at"<<i-j<<endl;
j = reset[j];
}
}
}
int main(int argc, char const *argv[])
{
/* code */
for(int i = 0; i < MAX_N; i++) {
reset[i] = -1;
}
string str, pat;
cin>>str>>pat;
KMPsearch(str, pat);
return 0;
}