KMP

fsjhhh Lv2

KMP

例题:洛谷P3375

表示存在最大的, 使得

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
struct KMP {
std::string S, T;
int s_len, t_len;
std::vector<int> ne;
std::vector<int> pos;

KMP() {}
KMP(std::string& s, std::string& t) {
init(s, t);
}

void init(std::string& s, std::string& t) {
S = s;
T = t;
s_len = S.size();
t_len = T.size();
ne.resize(t_len, 0);
pos.clear();
}

void get_next() { // 求next数组
ne[0] = 0;
for (int i = 1, j = 0; i < t_len; i++) {
while (j && T[j] != T[i]) {
j = ne[j - 1];
}
if (!j && T[j] != T[i]) {
continue;
}
j ++ ;
ne[i] = j;
}
}

void get_pos() { // 求出现位置
get_next();
for (int i = 0, j = 0; i < S.size(); i++) {
while (j && S[i] != T[j]) {
j = ne[j - 1];
}
if (!j && S[i] != T[j]) {
continue;
}
j ++ ;
if (j == t_len) {
pos.push_back(i - j + 1);
j = ne[j - 1];
}
}
}

};
  • 标题: KMP
  • 作者: fsjhhh
  • 创建于 : 2024-02-13 10:23:09
  • 更新于 : 2024-08-09 14:43:26
  • 链接: https://fsjhhh.github.io/2024/02/13/KMP/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
此页目录
KMP