Advertisement
urmisaha

Z algorithm

Oct 23rd, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. #define maxm 10001
  3.  
  4. using namespace std;
  5.  
  6. int L, R, k;
  7. string str, patt, S;
  8.  
  9. void calculateZ(){
  10.     vector<int> Z(S.size());
  11.     L = R = 0;
  12.     for(int i=1; i<S.size(); ++i){
  13.         if(i > R){
  14.             L = R = i;
  15.             while(R < S.size() && S[i] == S[R-L]){
  16.                 R++;
  17.             }
  18.             Z[i] = R - L;
  19.             R--;
  20.         }
  21.         else{
  22.             k = i - L;
  23.             if(Z[k] < R - i + 1){
  24.                 Z[i] = Z[k];
  25.             }
  26.             else{
  27.                 while(R < S.size() && S[i] == S[R-L]){
  28.                     R++;
  29.                 }
  30.                 Z[i] = R - L;
  31.                 R--;
  32.             }
  33.         }
  34.     }
  35.     cout<<"Z = ";
  36.     for(int i=0; i<S.size(); ++i)
  37.         cout<<Z[i]<<" ";
  38.     cout<<"\nPositions in string:\n";
  39.     for(int i=patt.size()+1; i<S.size(); ++i)
  40.         cout<<Z[i]<<" ";
  41.     cout<<"\n";
  42. }
  43.  
  44.  
  45. int main(){
  46.     S="";
  47.     cin>>str>>patt;
  48.     S += patt + "$" + str;
  49.     calculateZ();
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement