-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathKMP Algorithm.cpp
More file actions
70 lines (60 loc) · 1.27 KB
/
KMP Algorithm.cpp
File metadata and controls
70 lines (60 loc) · 1.27 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
62
63
64
65
66
67
68
69
70
/*input
aaaaaab
aaa
*/
/* Pattern Searching Alogrithm
Time Complexity: O(n)
*/
#include <iostream>
#include <string>
// LPS = Longest Propre Prefix Subsequence which is also a suffix
const int N = 10000;
int lps[N];
void LPS(std::string pattern)
{
int m = pattern.length(), i = 1, len = 0;
lps[0] = 0;
while(i < m) {
if(pattern[i] == pattern[len]) {
lps[i ++] = ++len;
}
else {
if(!len) lps[i ++] = 0;
else len = lps[len - 1];
}
}
}
void KMP(std::string text, std::string pattern)
{
int m = pattern.length();
int n = text.length();
LPS(pattern);
int i = 0, j = 0;
while(i < n) {
if(pattern[j] == text[i]) {
i ++;
j ++;
}
if(j == m) {
std::cout << "Pattern found at index " << i - j + 1 << "\n";
j = lps[j - 1];
}
else if(i < n and pattern[j] != text[i]) {
if(!j) i ++;
else j = lps[j - 1];
}
}
}
int main()
{
std::string pattern, text;
std::cin >> text >> pattern;
KMP(text, pattern);
return 0;
}
/* Expected Output
Pattern found at index 1
Pattern found at index 2
Pattern found at index 3
Pattern found at index 4
*/