-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathKMP.cpp
More file actions
40 lines (37 loc) · 747 Bytes
/
KMP.cpp
File metadata and controls
40 lines (37 loc) · 747 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
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define MAX_N 100005
int reset[MAX_N];
void kmp_pre(string pat){
int i=0,j=1;
reset[0]=-1;
while(j>=0 && pat[i]!=pat[j]){
j=reset[j];
}
i++,j++;
reset[i]=j;
}
void kmp_search(string str,string pat){
kmp_pre(pat);
int i=0,j=0;
while(i<str.size()){
while(j>=0 && str[i]!=pat[j]){
j=reset[j];
}
i++,j++;
if(j==pat.size()){
cout<<"pattern is found at"<<i-j<<endl;
j=reset[j];//for next occurence
}
}
}
int main() {
for(int i=0;i<MAX_N;i++){
reset[i]=-1;
}
string str,pat;
cin>>str>>pat;
kmp_search(str,pat);
return 0;
}