-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKmp.cpp
More file actions
39 lines (36 loc) · 893 Bytes
/
Kmp.cpp
File metadata and controls
39 lines (36 loc) · 893 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
#include <bits/stdc++.h>
using namespace std;
vector<int> prefix(string s){
vector<int> pi(s.size(),0);
for(int i = 1;i < s.size();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_search(string s,string t){
vector<int> pi = prefix(t);
vector<int> indices;
int i = 0;
int j = 0;
int n = s.size();
int m = t.size();
while(n-i >= m-j){
if(s[i] == t[j]){
i++;
j++;
}
if(j == t.size()){
indices.push_back(i-j);
j = pi[j-1];
}else if(i < s.size() && s[i] != t[j]){
if(j != 0) j = pi[j-1];
else i++;
}
}
return indices;
}
int main(){
}