-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathnaiveSearch.cpp
78 lines (63 loc) · 1.36 KB
/
naiveSearch.cpp
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
71
72
73
74
75
76
77
78
/*
* @author : imkaka
* @date : 1/2/2019
*/
#include<iostream>
#include<string>
using namespace std;
void computeLPS(string, int, int []);
// KMP Algorithm
void KMPsearch(string text, string pat){
// Length
int N = text.size();
int M = pat.size();
// Define LPS (Longest Proper Prefix)
int lps[M];
//Preprocess
computeLPS(pat, M, lps);
int i = 0, j = 0;
while(i < N){
//While Match
if(pat[j] == text[i]){
i++;
j++;
}
if(j == M){
cout << "Pattern Found At " << (i-j) << endl;
j = lps[j-1];
}
else if(i < N && pat[j] != text[i]){
if(lps[j] != 0)
j = lps[j-1];
else
i++;
}
}
}
void computeLPS(string pat, int M, int lps[]){
int len = 0; //Track len of longest common prefix which is suffix also.
lps[0] = 0;
int i = 1;
while(i < M){
if(pat[i] == pat[len]){
len++;
lps[i] = len;
i++;
}
else{
if(len != 0){
len = lps[len-1]; //Don't increment i
}
else{
lps[i] = 0;
i++;
}
}
}
}
int main(){
string txt = "ABABDABACDABABCABAB";
string pat = "ABABCABAB";
KMPsearch(txt, pat);
return 0;
}