-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKMP_algorithm.c++
70 lines (56 loc) · 1.3 KB
/
KMP_algorithm.c++
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
59
60
61
62
63
64
65
66
67
68
69
70
#include<iostream>
#include<string.h>
using namespace std;
void prefixlps(char *pattern,int m,int *lps){
int len = 0; //variable to assist on traversal
lps[0] = 0;
int i = 1;
while(i < m){ //find a match,increment
if(pattern[i] == pattern[len]){
len++;
lps[i] = len;
i++;
}
else{ //match not found and len not equal
if(len != 0){
len = lps[len-1];
}
else{
lps[i] = 0;
i++;
}
}
}
for (int z=0;z<m;z++){
cout<<lps[z]<<" ";}
}
void kmpsearch(char *text,char *pattern){
int n = strlen(text);
int m = strlen(pattern);
int lps[m];
prefixlps(pattern,m,lps);
int i = 0,j = 0;
while((n - i) >= (m - j)){
if(pattern[j] == text[i]){
i++,j++;
}
else{
if(j!=0){
j = lps[j-1];
}
else{
i=i+1;
}
}
if(j==m){
cout << "Pattern is found"<<" ";
j = lps[j-1];
}
}
}
int main(){
char text[] = "ababcabcababaab";
char pattern[] = "baab";
kmpsearch(text,pattern);
return 0;
}