Pagini recente » Cod sursa (job #2836556) | Cod sursa (job #527516) | Cod sursa (job #1584603) | Cod sursa (job #2905352) | Cod sursa (job #3238257)
#include <fstream>
#include <vector>
using namespace std;
ifstream f("strmatch.in");
ofstream g("strmatch.out");
string pattern, str;
vector<int> computeLPS(string pattern) {
int m = pattern.size();
vector<int> lps(m, 0);
int i = 1;
int length = 0;
while (i < m) {
if (pattern[i] == pattern[length]) {
length++;
lps[i++] = length;
} else {
if (length != 0) {
length = lps[length - 1];
} else {
lps[i] = 0;
i++;
}
}
}
return lps;
}
vector <int> searchKMP(string pattern, string str) {
vector<int>result;
int n = str.size();
int m = pattern.size();
vector<int> lps = computeLPS(pattern);
int i = 0, j = 0;
while (i < n) {
if (str[i] == pattern[j]) {
i++;
j++;
}
if (j == m) {
result.push_back(i - j);
j = lps[j - 1];
} else {
if (i < n && str[i] != pattern[j]) {
if (j == 0) {
i++;
} else {
j = lps[j - 1];
}
}
}
}
return result;
}
int main() {
f >> pattern >> str;
vector<int> result = searchKMP(pattern, str);
int matches = result.size();
g << matches << '\n';
for (int i = 0; i < min(matches, 1000); i++) {
g << result[i] << " ";
}
}