Pagini recente » Cod sursa (job #3251500) | Cod sursa (job #2422405) | Cod sursa (job #926763) | Cod sursa (job #2696453) | Cod sursa (job #2031795)
#include <fstream>
#include <string>
#include <vector>
using namespace std;
vector<int> FindPrefix(const string &s)
{
vector<int> prefix(s.size(), 0);
int len = 0;
for (size_t i = 1; i < s.size(); ++i) {
while (len > 0 && s[i] != s[len]) {
len = prefix[len - 1];
}
if (s[i] == s[len]) {
len += 1;
}
prefix[i] = len;
}
return prefix;
}
pair<int, vector<int>> FindMatches(const string &text, const string &pattern)
{
vector<int> matches;
int match_count = 0;
auto prefix = FindPrefix(pattern);
int len = 0;
for (size_t i = 0; i < text.size(); ++i) {
auto ch = text[i];
while (len > 0 && ch != pattern[len]) {
len = prefix[len - 1];
}
if (ch == pattern[len]) {
len += 1;
}
if (len == (int)pattern.size()) {
match_count += 1;
if (match_count <= 1000) {
matches.push_back(i - len + 1);
}
}
}
return { match_count, matches };
}
int main()
{
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
string pattern, text;
getline(fin, pattern);
getline(fin, text);
auto matches = FindMatches(text, pattern);
fout << matches.first << "\n";
for (const auto &elem : matches.second) {
fout << elem << " ";
}
return 0;
}