forked from arijitAD/Awesome-Algorithmic-Coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKMP.cpp
More file actions
61 lines (51 loc) · 1.22 KB
/
KMP.cpp
File metadata and controls
61 lines (51 loc) · 1.22 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
59
60
61
// KMP Algorithm
# include <bits/stdc++.h>
#define all(a) (a).begin(),(a).end()
#define gcd __gcd
#define bitcount __builtin_popcount
using namespace std;
typedef std::vector<int> vi;
typedef std::vector<std::string> vs;
typedef std::pair<int, int> pii;
typedef std::set<int> si;
typedef std::map<std::string, int> msi;
vi PrefixFunction(string pattern){
int PatternLength = pattern.length() ;
vi PrefixTable(PatternLength) ;
PrefixTable[0] = 0 ;
int i = 0 ;
for(int j=1; j<PatternLength; j++){
while(i>0&&pattern[i]!=pattern[j]){
i = PrefixTable[i] ;
}
if(pattern[i]==pattern[j]){
i = i + 1 ;
}
PrefixTable[j] = i ;
}
return PrefixTable ;
}
void KMP(string text, string pattern){
vi PrefixTable = PrefixFunction(pattern) ;
int PatternLength = pattern.length() ;
int TextLength = text.length() ;
int j = 0 ;
for(int i=0; i<TextLength; i++) {
while(j>0&&pattern[j]!=text[i]){
j = PrefixTable[j] ;
}
if(pattern[j]==text[i]){
j = j + 1;
}
if(j==PatternLength){
cout<<"Found at position (index 0): "<< (i-PatternLength)+1 << endl ;
j = PrefixTable[j] ;
}
}
}
int main(int argc, char const *argv[]){
string text, pattern ;
cin >> text >> pattern ;
KMP(text, pattern) ;
return 0;
}