Pagini recente » Cod sursa (job #2043060) | Cod sursa (job #2221242) | Cod sursa (job #1661483) | Cod sursa (job #1523076) | Cod sursa (job #1830931)
#include <fstream>
#include <string>
#include <vector>
using std::ifstream;
using std::ofstream;
using std::string;
using std::vector;
string input, substr;
vector<int> KMP(string input, string substr) {
vector<int> positions(substr.size() + 1, -1);
vector<int> result;
unsigned int substr_size = substr.size();
unsigned int input_size = input.size();
for (unsigned int i = 1; i <= substr_size; i++) {
int pos = positions.at(i - 1);
while (pos != -1 && substr[pos] != substr[i - 1]) pos = positions.at(pos);
positions.at(i) = pos + 1;
}
int pos_input = 0, pos_substr = 0;
while (pos_input < input_size) {
while (pos_substr != -1 && (substr[pos_substr] != input[pos_input] || pos_substr == substr_size)) pos_substr = positions.at(pos_substr);
pos_substr++;
pos_input++;
if (pos_substr == substr_size) result.push_back(pos_input - pos_substr);
}
return result;
}
ifstream in("strmatch.in");
ofstream out("strmatch.out");
int main() {
in >> substr >> input;
vector<int> result = KMP(input, substr);
out << result.size() << '\n';
for (unsigned int i = 0; i < result.size(); i++) { if (i == 1000) break; out << result.at(i) << ' '; }
}