Advertisement
LinKin

Z-algorithm

Feb 24th, 2012
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.66 KB | None | 0 0
  1. /*
  2.  * Algorithm: z-algorithm
  3.  * Order : linear O(n)
  4.  */
  5. #include<stdio.h>
  6. #include<string.h>
  7. #define MAX 100007
  8. char str[MAX+7],n; // n str len
  9. long z[MAX+7];
  10. void Z_Alg( void )
  11. {
  12.     long i,L = 0,R = 0;
  13.     z[0] = 0;   // set on ur own
  14.     for( i=1;i<n;i++ ){
  15.         if (i > R) {
  16.             L = R = i;
  17.             while( R < n && str[R-L] == str[R] ) R++;
  18.             z[i] = R-L; R--;
  19.         }
  20.         else{
  21.             long k = i-L;
  22.             if( z[k] < R-i+1) z[i] = z[k];
  23.             else{
  24.                 L = i;
  25.                 while( R < n && str[R-L] == str[R] ) R++;
  26.                 z[i] = R-L; R--;
  27.             }
  28.         }
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement