Advertisement
Domerk

КМП

Jan 21st, 2012
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. // Реализация алгоритма КМП, отсюда: http://ru.wikibooks.org/wiki/%D0%9F%D1%80%D0%B8%D0%BC%D0%B5%D1%80%D1%8B_%D1%80%D0%B5%D0%B0%D0%BB%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D0%B8_%D0%B0%D0%BB%D0%B3%D0%BE%D1%80%D0%B8%D1%82%D0%BC%D0%B0_%D0%9A%D0%BD%D1%83%D1%82%D0%B0_%E2%80%94_%D0%9C%D0%BE%D1%80%D1%80%D0%B8%D1%81%D0%B0_%E2%80%94_%D0%9F%D1%80%D0%B0%D1%82%D1%82%D0%B0
  2.  
  3. # include <string>
  4. # include <vector>
  5.  
  6. using namespace std;
  7.  
  8. string::size_type KMP(const string& S, int begin, const string& pattern){
  9.         vector<int> pf (pattern.length());
  10.  
  11.         pf[0] = 0;
  12.         for (int k = 0, i = 1; i<pattern.length(); ++i){
  13.                 while(k>0 && pattern[i] != pattern[k])
  14.                         k = pf[k-1];
  15.  
  16.                 if (pattern[i] == pattern[k])
  17.                         k++;
  18.  
  19.                 pf[i] = k;
  20.         }
  21.  
  22.         for (int k = 0, i = begin; i<S.length(); ++i){
  23.                 while ((k>0) && (pattern[k] != S[i]))
  24.                         k = pf[k-1];
  25.  
  26.                 if (pattern[k] == S[i])
  27.                         k++;
  28.  
  29.                 if (k==pattern.length())
  30.                         return (i-pattern.length()+1);//либо продолжаем поиск следующих вхождений
  31.         }
  32.  
  33.         return (string::npos);
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement