Pagini recente » Cod sursa (job #5668) | Cod sursa (job #1801162) | Cod sursa (job #1890073) | Cod sursa (job #1293694) | Cod sursa (job #1833920)
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
std::vector<int> prefix(std::string needle)
{
std::vector<int> pi((int)needle.size(),0);
int k=0;
for(int i=1;i<(int)needle.size();i++)
{
while(needle[i]!=needle[k] && k>0)
k=pi[k-1];
if(needle[i]==needle[k])
k++;
pi[i]=k;
}
return pi;
}
std::vector<int> kmp(std::string haystack, std::string needle)
{
std::vector<int> sol,pi=prefix(needle);
int k=0;
for(int i=0;i<(int)haystack.size();i++)
{
while(haystack[i]!=needle[k] && k>0)
k=pi[k-1];
if(haystack[i]==needle[k])
k++;
if(k==(int)needle.size())
sol.push_back(i-(int)needle.size());
}
return sol;//sol contains starting position of occurrences of string needle in string haystack
}
int main()
{
std::ifstream in("strmatch.in");
std::string haystack,needle;
in>>needle>>haystack;
in.close();
std::vector<int> sol=kmp(haystack,needle);
std::ofstream out("strmatch.out");
out<<sol.size()<<'\n';
for(int i=0;i<std::min(1000,(int)sol.size());i++)
out<<sol[i]+1<<' ';
out.close();
return 0;
}