Advertisement
Guest User

Untitled

a guest
May 24th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.15 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> KnuthMorrisPratt(string pattern, string text, int Begin)
  5. {
  6.     vector <int> result;
  7.     vector <int> preff(pattern.size());
  8.     preff[0] = 0;
  9.     for(int i = 1, k = 0; i < pattern.size(); i++)
  10.     {
  11.         while(k > 0 && pattern[i] != pattern[k])
  12.         {
  13.             k = preff[k - 1];
  14.         }
  15.             if(pattern[i] == pattern[k])
  16.                 k++;
  17.         preff[i] = k;
  18.     }
  19.     for(int k = 0, i = Begin; i < text.size(); i++)
  20.     {
  21.         while(k > 0 && pattern[k] != text[i])
  22.             k = preff[k - 1];
  23.         if(pattern[k] == text[i])
  24.             k++;
  25.         if(k == pattern.size())
  26.             result.push_back(i - pattern.size() + 1);
  27.     }
  28.     return result;
  29. }
  30.  
  31. int main()
  32. {
  33.     ifstream in("input.txt");
  34.     ofstream out("search1.txt");
  35.  
  36.     string p; //substring
  37.     string t; //input string
  38.     in >> p >> t;
  39.  
  40.     vector<int> result = KnuthMorrisPratt(p, t, 0);
  41.     out << result.size() << endl;
  42.     for(int i = 0; i < result.size(); i++)
  43.     {
  44.         out << result[i] + 1 << ' ';
  45.     }
  46.     in.close();
  47.     out.close();
  48.     return 0;
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement