-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcses_1753.cpp
More file actions
57 lines (54 loc) · 1.04 KB
/
cses_1753.cpp
File metadata and controls
57 lines (54 loc) · 1.04 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
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int cnt = 0;
// KMP-algorithm
string str, tar;
cin >> str >> tar;
vector<int> next(1, 0);
int pre = 0; // 共同前後綴長度
// 算next陣列
for (int i = 1; i < tar.size();)
{
if (tar[pre] == tar[i])
{
pre++;
i++;
next.emplace_back(pre);
}
else
{
if (pre == 0)
{
next.emplace_back(0);
i++;
}
else
{
pre = next[pre - 1];
}
}
}
// 字串比對
for (int i = 0, j = 0; i < str.size();)
{
if (str[i] == tar[j])
i++, j++;
else if (j > 0)
j = next[j - 1];
else
i++;
if (j == tar.size())
{
cnt++;
j = next[j - 1];
}
}
cout << cnt << '\n';
return 0;
}