NP-Nidzo

KMP Algorithm

Aug 11th, 2020
1,068
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1.  
  2. /**------------------------
  3.     Author : NikolaP
  4.     Compiler : C++
  5. -------------------------*/
  6.  
  7. //{         Setup
  8.  
  9.     #include <bits/stdc++.h>
  10.     using namespace std;
  11.  
  12.     typedef long long int ll;
  13.     typedef long double ld;
  14.     typedef vector<int> vi;
  15.  
  16.     const int inf = INT_MAX;
  17.     const bool debug = 0;
  18.  
  19. //}
  20.  
  21. struct KMP{
  22.     string text, pattern;
  23.     vi key;
  24.  
  25.     void process(){
  26.         int len = pattern.size();
  27.         key.assign(len+1,0);
  28.  
  29.         int i = 0, j = -1;
  30.         key[0] = -1;
  31.  
  32.         while(i < len){
  33.             while(j >= 0 and pattern[i] != pattern[j]) j = key[j];
  34.             i++; j++;
  35.             key[i] = j;
  36.         }
  37.     }
  38.  
  39.     KMP(string _text, string _pattern){
  40.         text = _text;
  41.         pattern = _pattern;
  42.         process();
  43.     }
  44.  
  45.     void Solution(){
  46.         int i = 0, j = 0;
  47.         while(i < text.size()){
  48.             while(j >= 0 and text[i] != pattern[j]) j = key[j];
  49.             i++; j++;
  50.             if(j == pattern.size()){
  51.                 cout << "Index: " << i-j << '\n';
  52.                 j = key[j];
  53.             }
  54.         }
  55.     }
  56. };
  57.  
  58.  
  59. int main()
  60. {
  61.     ios::sync_with_stdio(false);
  62.     cin.tie(0);
  63.     cout.precision(8);
  64.     //cout << fixed;
  65.  
  66.     string a,b;
  67.     getline(cin,a);
  68.     getline(cin,b);
  69.  
  70.     KMP kmp = KMP(a,b);
  71.     kmp.Solution();
  72.     return 0;
  73. }
  74.  
  75.  
  76.  
  77.  
Advertisement
Add Comment
Please, Sign In to add comment