-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKMP.cpp
67 lines (58 loc) · 1.08 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
#include <string>
#include <vector>
using namespace std;
vector<int> border(string S)
{
int n = (int)S.size();
vector<int> B(n+1);
B[0] = -1;
int j = -1;
for (int i=1; i<=n; i++)
{
while (j>=0 && S[i-1]!=S[j])
j = B[j];
j++;
B[i] = j;
}
return B;
}
// B = border(P)
vector<int> search(string T, string P, vector<int> B)
{
int n = (int)T.size();
int m = (int)P.size();
vector<int> A;
int j = 0;
for (int i=0; i+m<=n;)
{
if (j<m && T[i+j]==P[j])
{
j++;
if (j==m)
A.push_back(i);
}
else
{
i += j-B[j];
if (j>0)
j = B[j];
}
}
return A;
}
#include <iostream>
int main()
{
string T = "abc abcdab abcdabcdabde abcdabd";
string P = "abcdabd";
vector<int> B = border(P);
// -1 0 0 0 0 1 2 0
for (int b: B)
cout<<" "<<b;
cout<<endl;
// 15 24
vector<int> A = search(T, P, B);
for (int a: A)
cout<<" "<<a;
cout<<endl;
}