Pagini recente » Cod sursa (job #3353081) | Cod sursa (job #1090193) | Cod sursa (job #1265058) | Cod sursa (job #907763) | Cod sursa (job #3319679)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int MAX = 2000000;
void computeLPS(const string &pattern, int lps[]) {
int m = pattern.size();
lps[0] = 0;
int len = 0;
int i = 1;
while (i < m) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0)
len = lps[len - 1];
else {
lps[i] = 0;
i++;
}
}
}
}
void KMPsearch(const string &text, const string &pattern, int poz[], int &count) {
int n = text.size();
int m = pattern.size();
int lps[MAX];
computeLPS(pattern, lps);
int i = 0;
int j = 0;
count = 0;
while (i < n) {
if (text[i] == pattern[j]) {
i++;
j++;
}
if (j == m) {
if (count < 1000)
poz[count] = i - j;
count++;
j = lps[j - 1];
} else if (i < n && text[i] != pattern[j]) {
if (j != 0)
j = lps[j - 1];
else
i++;
}
}
}
int main() {
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
string pattern, text;
getline(fin, pattern);
getline(fin, text);
int poz[1000];
int count;
KMPsearch(text, pattern, poz, count);
fout << count << "\n";
for (int i = 0; i < count && i < 1000; i++)
fout << poz[i] << (i == min(count, 1000) - 1 ? "\n" : " ");
return 0;
}