0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-11-30 16:56:27 +00:00

P3375 【模板】KMP字符串匹配

R67840678
This commit is contained in:
Baoshuo Ren 2022-01-25 09:28:09 +08:00
parent d4301084bc
commit b639acb766
Signed by: baoshuo
GPG Key ID: 70F90A673FB1AB68

View File

@ -5,27 +5,29 @@ using std::cin;
using std::cout; using std::cout;
using std::endl; using std::endl;
int border[1000005]; const int N = 1000005;
int f[N], next[N];
std::string s1, s2; std::string s1, s2;
int main() { int main() {
cin >> s1 >> s2; cin >> s1 >> s2;
for (int i = 0; i < s1.size(); i++) { next[0] = -1;
bool flag = false; for (int i = 1, j = -1; i < s2.size(); i++) {
if (s1.substr(i, s2.size()) == s2) { while (j != -1 && s2[i] != s2[j + 1]) j = next[j];
cout << i + 1 << endl; if (s2[i] == s2[j + 1]) j++;
next[i] = j;
}
for (int i = 0, j = -1; i < s1.size(); i++) {
while (j != -1 && (j == s2.size() || s1[i] != s2[j + 1])) j = next[j];
if (s1[i] == s2[j + 1]) j++;
if (j == s2.size() - 1) {
cout << i - j + 1 << endl;
f[i] = j;
} }
} }
for (int i = 0; i < s2.size(); i++) { for (int i = 0; i < s2.size(); i++) {
bool flag = false; cout << next[i] + 1 << ' ';
for (int j = i; j > 0; j--) {
if (s2.substr(0, j) == s2.substr(i - j + 1, j)) {
flag = true;
cout << j << ' ';
break;
}
}
if (!flag) cout << 0 << ' ';
} }
cout << endl; cout << endl;
return 0; return 0;