-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkmp.cpp
More file actions
57 lines (49 loc) · 852 Bytes
/
kmp.cpp
File metadata and controls
57 lines (49 loc) · 852 Bytes
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
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5;
string p,t;
int a[N];
vector<int> ans;
void cra()
{
int i = 1,j = 0;
while(i<p.length())
{
if(p[i]==p[j])
{
a[i] = j+1;
i++;
j++;
}
else
{
if(j==0){ a[i] = 0; i++; }
else j = a[j-1];
}
}
}
void solve()
{
int i = 0,j = 0;
while(i<t.length())
{
if(t[i]==p[j])
{
i++; j++;
if(j==p.length()){ ans.push_back(i-p.length()); j = a[j-1]; }
}
else
{
if(j>0) j = a[j-1];
else i++;
}
}
}
int main()
{
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> p >> t;
cra();
solve();
for(int i = 0;i < ans.size();i++) cout << ans[i] << ' ';
}