-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkmp.cpp
More file actions
63 lines (59 loc) · 1.28 KB
/
kmp.cpp
File metadata and controls
63 lines (59 loc) · 1.28 KB
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
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector<int> kmp_preprocess(const string &needle)
{
int m = needle.size();
vector<int> pi(m);
int j = 0;
for (int i = 1; i < m; i++)
{
while (j != 0 && needle[i] != needle[j])
{
j = pi[j - 1];
}
if (needle[i] == needle[j])
{
j++;
}
pi[i] = j;
}
return pi;
}
vector<int> kmp_search(const string &haystack, const string &needle)
{
int n = haystack.size(), m = needle.size();
vector<int> pi = kmp_preprocess(needle); // 用来存储next数组
vector<int> matches;
int j = 0;
for (int i = 0; i < n; i++)
{
while (j != 0 && haystack[i] != needle[j])
{
j = pi[j - 1];
}
if (haystack[i] == needle[j])
{
j++;
}
if (j == m)
{
matches.push_back(i - m + 1);
j = pi[j - 1];
}
}
return matches;
}
int main()
{
string haystack, needle;
cin >> haystack >> needle;
vector<int> matches = kmp_search(haystack, needle);
for (int i : matches)
{
cout << i << " ";
}
cout << endl;
return 0;
}