Pagini recente » Cod sursa (job #1282393) | Cod sursa (job #3191173) | Cod sursa (job #1224495) | Cod sursa (job #2718874) | Cod sursa (job #2247045)
#include <fstream>
#include <string>
#include <vector>
using namespace std;
vector<int> FindPrefix(const string &str)
{
vector<int> prefix(str.size());
prefix[0] = -1;
auto index = -1;
for (size_t i = 1; i < str.size(); i += 1) {
while (index >= 0 && str[index + 1] != str[i]) {
index = prefix[index];
}
if (str[index + 1] == str[i]) {
index += 1;
}
prefix[i] = index;
}
return prefix;
}
pair<int, vector<int>> FindMatches(const string &word, const string &text)
{
static constexpr int kMatchLimit = 1000;
auto count = 0;
vector<int> pos;
auto prefix = FindPrefix(word);
auto index = -1;
for (size_t i = 0; i < text.size(); i += 1) {
while (index >= 0 && word[index + 1] != text[i]) {
index = prefix[index];
}
if (word[index + 1] == text[i]) {
index += 1;
}
if (index + 1 >= (int)word.size()) {
if (count < kMatchLimit) {
pos.push_back(i - word.size() + 1);
}
count += 1;
}
}
return {count, pos};
}
int main()
{
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
string word, text;
getline(fin, word);
getline(fin, text);
auto matches = FindMatches(word, text);
fout << matches.first << "\n";
for (const auto &pos : matches.second) {
fout << pos << " ";
}
fout << "\n";
return 0;
}