-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathKMP.cpp
More file actions
56 lines (53 loc) · 1022 Bytes
/
KMP.cpp
File metadata and controls
56 lines (53 loc) · 1022 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
#include<set>
#include<map>
#include<cmath>
#include<stack>
#include<queue>
#include<array>
#include<cstdio>
#include<bitset>
#include<vector>
#include<utility>
#include<sstream>
#include<cstring>
#include <climits>
#include <fstream>
#include<iostream>
#include<algorithm>
#include <functional>
#define mp make_pair
using namespace std;
vector<int> pre( string &s ){
int n = s.size();
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++;// if current match
pi[i] = j;
}
return pi;
}
vector<int> KMP(string &l, string &s ){
int j = 0;
vector<int> idx;
int n = l.size();
int m = s.size();
vector<int> pi = pre(s);
for( int i = 0; i < n; i++ ){
while( j > 0 && l[i] != s[j] ){
j = pi[j-1];
}
if( l[i] == s[j] )j++;
if( j == m )idx.push_back(i-m+1);
}
return idx;
}
int main(){
string large, small;
cin >> large >> small;
vector<int> idx = KMP(large, small);
for( auto it : idx ){
cout << it << " ";
}
}