Pagini recente » Cod sursa (job #1045605) | Cod sursa (job #3139123) | Cod sursa (job #1152160) | Cod sursa (job #577908) | Cod sursa (job #2087082)
#include <fstream>
#include <string>
#include <vector>
using namespace std;
ifstream f("strmatch.in");
ofstream g("strmatch.out");
vector<int> makePrefix (string pattern) {
vector<int> F (pattern.length() + 1, 0);
int j = 0;
for (int i = 2; i <= pattern.length(); i++) {
j = F[i - 1];
while (true) {
if (pattern[j] == pattern [i - 1]) {
F[i] = j + 1;
break;
}
if (j == 0) {
F[i] = 0;
break;
}
j = F[j];
}
}
return F;
}
vector<int> kmp(string text, string pattern) {
vector<int> F = makePrefix(pattern);
int indexText = 0, indexPattern = 0, countMatch = 0;
vector<int> solution;
while(true) {
if (indexText == text.length()) {
break;
}
if (text[indexText] == pattern[indexPattern]) {
++indexText;
++indexPattern;
if(indexPattern == pattern.length()) {
solution.push_back(indexText - indexPattern);
countMatch++;
if(countMatch == 1000) {
break;
}
indexPattern = F[indexPattern];
}
}else if (indexPattern > 0) {
indexPattern = F[indexPattern];
}else {
indexText++;
}
}
return solution;
}
int main()
{
/*vector <int> preffixMatch = makePrefix("ABABC");
for (vector<int>::iterator it = preffixMatch.begin(); it != preffixMatch.end(); it++) {
cout<<*it<<" ";
}*/
string pattern, text;
f>>pattern>>text;
vector <int> solution = kmp(text, pattern);
g<<solution.size()<<"\n";
for (vector<int>::iterator it = solution.begin(); it != solution.end(); it++) {
g<<*it<<" ";
}
return 0;
}