forked from rituburman/hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.cpp
More file actions
58 lines (54 loc) · 1.18 KB
/
KMP.cpp
File metadata and controls
58 lines (54 loc) · 1.18 KB
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
58
#include <bits/stdc++.h>
using namespace std;
vector<int> computelps(string str){
vector<int> lps(str.size());
lps[0]=0;
int j=0;
for(int i=1;i<str.size();i++){
while(j!=0 && str[j]!=str[i]){
j=lps[j-1];
}
if(str[j]==str[i]){
j++;
}
lps[i]=j;
}
return lps;
}
bool kmpsearch(string tofind,string text){
vector<int> lps = computelps(tofind);
cout<<endl;
int n = text.size(), m = tofind.size();
int i = 0, j = 0;
while( i < n ){
while( j < m && i < n && tofind[j] == text[i] ){
i++;
j++;
}
if( j == m && tofind[j-1] == text[i-1]){
return 1;
}
else if( i == n ){
return 0;
}
else{
if( j != 0){
j = lps[j-1];
}
else{
i++;
}
}
}
return 0;
}
int main(){
string text = "ABCDDBCEFGHIJJKLLMNOPQQRSTUVWXXXYZZ";
string tofind = "BCDD";
if(kmpsearch(tofind,text)){
cout<<"Found "<<tofind<<" in "<<text<<endl;
}
else{
cout<<"Not found "<<tofind<<" in "<<text<<endl;
}
}