Pagini recente » Cod sursa (job #1347542) | Cod sursa (job #1925741) | Cod sursa (job #1001995) | Cod sursa (job #1983715) | Cod sursa (job #3170485)
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin("strmatch.in");
ofstream fout("strmatch.out");
int sol[1005], solutions;
void computeLPS(string pat, int length, int lps[]) {
int last = 0;
lps[last] = 0;
int i = 1;
while (i < length) {
if (pat[i] == pat[last])
lps[i++] = ++last;
else {
if (last != 0)
last = lps[last - 1];
else
lps[i++] = 0;
}
}
}
void kmp(string txt, string pat) {
int n = txt.size();
int m = pat.size();
int lps[m];
computeLPS(pat, m, lps);
int i = 0, j = 0;
while (n - i >= m - j) {
if (txt[i] == pat[j])
i++, j++;
if (j == m) {
sol[solutions++] = i - j;
j = lps[j - 1];
} else if (i < n && txt[i] != pat[j]){
if (j != 0)
j = lps[j - 1];
else
i++;
}
}
}
int main() {
string str, pattern;
fin >> pattern;
fin >> str;
kmp(str, pattern);
fout << solutions << "\n";
for (int i = 0; i < solutions && i < 1000; i++)
fout << sol[i] << " ";
}