-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKMP.cpp
68 lines (55 loc) · 1.14 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
#include <bits/stdc++.h>
using namespace std;
vector<int> prefix_function(string s)
{
int n = (int)s.length();
vector<int> pi(n);
for (int i = 1; i < n; i++)
{
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
vector<int> kmp(string txt, string pat)
{
int M = pat.length();
int N = txt.length();
vector<int> pi = prefix_function(pat), occurences;
int i = 0;
int j = 0;
while ((N - i) >= (M - j)) {
if (pat[j] == txt[i]) {
j++;
i++;
}
if (j == M) {
occurences.push_back(i-j);
j = pi[j - 1];
}
else if (i < N && pat[j] != txt[i]) {
if (j != 0)
j = pi[j - 1];
else
i = i + 1;
}
}
return occurences;
}
int main()
{
string text, pattern;
cin >> text;
cin >> pattern;
vector<int> occurences = kmp(text, pattern);
for (auto i : occurences)
{
cout << i << " ";
}
cout << "\n";
return 0;
}