KMP模板题,直接套就可以
cpp#include <iostream>
#include <vector>
using namespace std;
vector<int> get_border_lengths(const string& pattern) {
int m = pattern.length();
vector<int> border_lengths(m, 0);
int j = 0;
for (int i = 1; i < m; ++i) {
while (j > 0 && pattern[i] != pattern[j]) {
j = border_lengths[j - 1];
}
if (pattern[i] == pattern[j]) {
++j;
}
border_lengths[i] = j;
}
return border_lengths;
}
vector<int> find_occurrences(const string& text, const string& pattern) {
int n = text.length();
int m = pattern.length();
vector<int> occurrences;
vector<int> border_lengths = get_border_lengths(pattern);
int j = 0;
for (int i = 0; i < n; ++i) {
while (j > 0 && text[i] != pattern[j]) {
j = border_lengths[j - 1];
}
if (text[i] == pattern[j]) {
++j;
}
if (j == m) {
occurrences.push_back(i - m + 1);
j = border_lengths[j - 1];
}
}
return occurrences;
}
int main() {
string text, pattern;
cin >> text >> pattern;
vector<int> positions = find_occurrences(text, pattern);
for (int pos : positions) {
cout << pos + 1 << endl;
}
vector<int> border_lengths = get_border_lengths(pattern);
for (int len : border_lengths) {
cout << len << " ";
}
return 0;
}
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!