Pagini recente » Cod sursa (job #1237132) | Cod sursa (job #1383983) | Cod sursa (job #1780125) | Cod sursa (job #2843136) | Cod sursa (job #3242051)
#include <iostream>
#include <vector>
#include <fstream>
#include <string.h>
#define MAX 2000000
using namespace std;
ifstream in("strmatch.in");
ofstream out("strmatch.out");
int *createSubPatterns(string p){
int *lps = (int*) malloc(p.length() * sizeof(int));
int i = 1, j = 0;
while(i < p.length()){
if(p[i] == p[j]){
j++;
lps[i] = j;
i++;
}
else{
if(j > 0){
j = lps[j-1];
}
else{
lps[i] = 0;
i++;
}
}
}
return lps;
}
int main(){
string p, s;
vector<int> pos(1001);
getline(in, p);
getline(in, s);
int* lps = createSubPatterns(p);
/*
for(int i = 0; i<p.length(); i++)
cout << lps[i] << ", ";
cout << endl;
*/
/*
int j = 0, i = 0;
int matches = 0;
while(i < s.length()){
if(j == p.length()){
pos[matches++] = i;
j = lps[j-1];
if(matches == 1000)
break;
}
if(s[i] == p[j]){j++; i++;}
else if(j > 0){
j = lps[j-1];
}
else i++;
}
out << matches << endl;
for(int i = 0; i<matches; i++)
out << pos[i] - p.length() << " ";
*/
int j = 0, i = 0;
int matches = 0;
// KMP Search
while (i < s.length()) {
if (p[j] == s[i]) {
j++;
i++;
}
if (j == p.length()) {
// Found a match at index (i - j)
if (matches < 1000) {
pos[matches] = i - j;
}
matches++;
j = lps[j - 1]; // Prepare for the next possible match
} else if (i < s.length() && p[j] != s[i]) {
// Mismatch after j matches
if (j != 0) {
j = lps[j - 1];
} else {
i++;
}
}
}
// Output the results
out << matches << endl;
for (int k = 0; k < min(matches, 1000); k++) {
out << pos[k] << " ";
}
return 0;
}