0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-11-08 15:18:46 +00:00

#165. 【模板】KMP字符串匹配

https://sjzezoj.com/submission/52812
This commit is contained in:
Baoshuo Ren 2022-04-25 11:36:14 +08:00
parent 4850a27856
commit aad9d251b1
Signed by: baoshuo
GPG Key ID: 70F90A673FB1AB68

28
S2OJ/165/165.cpp Normal file
View File

@ -0,0 +1,28 @@
#include <iostream>
#include <string>
using std::cin;
using std::cout;
const char endl = '\n';
int nxt[1000005];
std::string s, p;
int main() {
cin >> s >> p;
nxt[0] = -1;
for (int i = 1, j = -1; i < p.size(); i++) {
while (j >= 0 && p[j + 1] != p[i]) j = nxt[j];
if (p[j + 1] == p[i]) j++;
nxt[i] = j;
}
for (int i = 0, j = -1; i < s.size(); i++) {
while (j != -1 && s[i] != p[j + 1]) j = nxt[j];
if (s[i] == p[j + 1]) j++;
if (j == p.size() - 1) {
cout << i - j + 1 << endl;
j = nxt[j];
}
}
return 0;
}