forked from Raju1822/HacktoberFest_2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMP.cpp
68 lines (62 loc) · 1.41 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;
const int MOD = 1e9 + 7;
void create_lps(string pat, int *lps)
{
int m = pat.size();
for (int i = 1; i < m; i++)
{
int j = lps[i - 1]; // j is index from where we should look for matching prefix and suffix
while (j > 0 and pat[i] != pat[j])
j = lps[j - 1];
if (pat[i] == pat[j])
j++;
lps[i] = j;
}
}
vector<int> kmp(string text, string pat)
{
vector<int> ans;
//algorithm to find occurences of pattern in given string;
int n = text.size(), m = pat.size();
int lps[m] = {0};
create_lps(pat, lps);
int i = 0, j = 0;
while (i < n)
{
if (text[i] == pat[j])
{
i++, j++;
}
if (j == m)
{
ans.push_back(i - j);
j = lps[j - 1];
}
else if (i < n and text[i] != pat[j])
{
if (j != 0)
j = lps[j - 1];
else
i++;
}
}
return ans;
}
int main()
{
int t = 1;
//cin >> t;
while (t--)
{
int n;
cin >> n;
string text, pat;
cin >> pat >> text;
vector<int> ans = kmp(text, pat);
if (ans.empty())
cout << "\n";
for (int i = 0; i < ans.size(); i++)
cout << ans[i] << "\n";
}
}