-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKMP.cpp
More file actions
48 lines (44 loc) · 714 Bytes
/
KMP.cpp
File metadata and controls
48 lines (44 loc) · 714 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
48
#include <bits/stdc++.h>
using namespace std;
#define MAX 100005
int reset[MAX];
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()
{
for(int i = 0; i < MAX; i++)
reset[i] = -1;
string str, pat;
cin>>str>>pat;
KMPsearch(str, pat);
return 0;
}