forked from ccgcv/Cplus-plus-for-hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMP.cpp
87 lines (81 loc) · 1.8 KB
/
KMP.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
79
80
81
82
83
84
85
86
87
#include <bits/stdc++.h>
using namespace std;
// lps is of pattern
// O(n+m) tIME AND o(m) SPACE
void fill_LPS(const string &pattern, vector<int> &lps)
{
int m = pattern.size();
// lenght of longest proper prefix suffix
lps[0] = 0; // as proper prefix of string length is 0
int i = 1; // starting from first
int len = 0; // in, starting len = 0
// len is previous length of matching
while (i < m)
{
// if next char matches with len
if (pattern[i] == pattern[len])
{
len++;
lps[i] = len;
i++;
}
else
{
if (len == 0)
{
lps[i] = 0;
i++;
}
else
{ // recusively search for next len
len = lps[len - 1];
}
}
}
}
void KMP(const string &text, const string &pattern)
{
int n = text.size();
int m = pattern.size();
vector<int> lps(m, 0);
fill_LPS(pattern, lps);
int i = 0, j = 0;
while (i < n)
{
// if match then move forward
if (pattern[j] == text[i])
{
i++;
j++;
}
// if after match , it is covers entire lenght of pat.
if (j == m)
{
cout << (i - j) << " ";
j = lps[j - 1]; //FIND THE NEXT TO MATCH
}
// if not match
else if (i < n and pattern[j] != text[i])
{
// if first charcater not matching
if (j == 0)
{
i++;
}
// search recursively
else
{
j = lps[j - 1];
}
}
}
}
int main()
{
string text;
cin >> text;
string pat;
cin >> pat;
KMP(text, pat);
return 0;
}