Pagini recente » Cod sursa (job #2046780) | Cod sursa (job #2944356) | Cod sursa (job #363825) | Cod sursa (job #2025254) | Cod sursa (job #1710735)
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
void PrefixFunction(const std::string& str, std::vector<int>& prefix){
int i, j;
j = 0;
prefix[0] = 0;
for (i = 1; i < prefix.size(); i++) {
while (j > 0 && str[j] != str[i]) {
j = prefix[j - 1];
}
if (str[i] == str[j]) {
j++;
}
prefix[i] = j;
}
}
void KMP(const std::string& str, const std::string& word){
int i, j;
int count;
i = 0;
j = 0;
std::vector<int> prefix(str.size());
std::vector<int> matches(1000);
int k;
count = 0;
k = 0;
std::ofstream g("strmatch.out");
PrefixFunction(word, prefix);
while (i < str.size()) {
while(str[i] == word[j] && j < word.size() && i < str.size()){
i++;
j++;
}
if(j == word.size()){
count++;
matches[k++] = i - word.size();
j = 0;
} else {
if (j > 0){
j = prefix[j - 1];
} else {
i++;
}
}
}
g << count;
for(i = 0; i < k; i++){
g << matches[k] << " ";
}
}
int main(){
std::string str;
std::string word;
std::ifstream f("strmatch.in");
std::getline(f,word);
std::getline(f,str);
f.close();
KMP(str,word);
return 0;
}