Pagini recente » Cod sursa (job #2800234) | Cod sursa (job #2122048) | Cod sursa (job #182127) | Cod sursa (job #228926) | Cod sursa (job #2404053)
#include <iostream>
#include <fstream>
#include <string>
#include <queue>
std::ifstream in("strmatch.in");
std::ofstream out("strmatch.out");
void PreProcessPattern(std::string pattern, int* LPS);
int KMP_Search(std::string pattern, std::string text, std::queue<int>& Solutii)
{
int Aparitii = 0;
int M = pattern.size();
int N = text.size();
int* LPS = new int[M];
PreProcessPattern(pattern, LPS);
int i = 0; //index for text
int j = 0; //index for pattern
while (i < N)
{
if (pattern[j] == text[i])
{
i++;
j++;
}
if(j == M)
{
Aparitii++;
Solutii.push(i-j);
j = LPS[j - 1];
}
else if(i < N && pattern[j] != text[i])
{
if (j != 0)
j = LPS[j - 1];
else
i++;
}
}
delete[] LPS;
return Aparitii;
}
void PreProcessPattern(std::string pattern, int* LPS)
{
//Length of the previous longest prefix suffix
int len = 0;
//LPS[0] is always 0
LPS[0] = 0;
//The loop calculates LPS[i]
int i = 1;
while (i < pattern.size())
{
if (pattern[i] == pattern[len])
{
len++;
LPS[i] = len;
i++;
}
else
{
if (len != 0)
{
len = LPS[len - 1];
}
else //len == 0
{
LPS[i] = 0;
i++;
}
}
}
}
int main()
{
std::queue<int> Solutii;
std::string pattern;
in >> pattern;
std::string text;
in >> text;
int Aparitii = KMP_Search(pattern, text, Solutii);
//int LPS[100];
//PreProcessPattern(pattern, LPS);
//std::cout << Aparitii;
out << Aparitii;
out << '\n';
int n = Solutii.size();
if (Solutii.size() > 999)
n = 1000;
while (n)
{
out << Solutii.front()<<" ";
Solutii.pop();
n--;
}
std::cin.get();
}