Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- vector<int> KnuthMorrisPratt(string pattern, string text, int Begin)
- {
- vector <int> result;
- vector <int> preff(pattern.size());
- preff[0] = 0;
- for(int i = 1, k = 0; i < pattern.size(); i++)
- {
- while(k > 0 && pattern[i] != pattern[k])
- {
- k = preff[k - 1];
- }
- if(pattern[i] == pattern[k])
- k++;
- preff[i] = k;
- }
- for(int k = 0, i = Begin; i < text.size(); i++)
- {
- while(k > 0 && pattern[k] != text[i])
- k = preff[k - 1];
- if(pattern[k] == text[i])
- k++;
- if(k == pattern.size())
- result.push_back(i - pattern.size() + 1);
- }
- return result;
- }
- int main()
- {
- ifstream in("input.txt");
- ofstream out("search1.txt");
- string p; //substring
- string t; //input string
- in >> p >> t;
- vector<int> result = KnuthMorrisPratt(p, t, 0);
- out << result.size() << endl;
- for(int i = 0; i < result.size(); i++)
- {
- out << result[i] + 1 << ' ';
- }
- in.close();
- out.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement