-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.cpp
More file actions
57 lines (53 loc) · 753 Bytes
/
KMP.cpp
File metadata and controls
57 lines (53 loc) · 753 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
49
50
51
52
53
54
55
56
57
//KMP Algorithm Implementation
#include <bits/stdc++.h>
using namespace std;
void pre(string s,int arr[]){
int n = s.length(),k;
arr[0]=-1;
for(int i=1;i<n;++i){
k = arr[i-1];
while(k>=0){
if(s[k]==s[i-1])
break;
else
k = arr[k];
}
arr[i]=k+1;
}
}
bool KMP(string pattern,string search){
int m = pattern.length();
int n = search.length();
int arr[m];
pre(pattern,arr);
int i=0,k=0;
while(i<n){
if(k==-1){
k=0;
i++;
}
else if(search[i]==pattern[k]){
i++;
k++;
if(k==m){
return 1;
}
}
else{
k=arr[k];
}
}
return 0;
}
int main(){
string search,pattern;
cin>>search>>pattern;
if(KMP(pattern,search)){
cout<<"Found ";
return 0;
}
else{
cout<<"Not Found ";
return 0;
}
}