Advertisement
LinKin

Smallest Cyclic Shift

Jul 6th, 2012
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.51 KB | None | 0 0
  1. /*
  2.  * Findin lex smallest cyclic shift of a string
  3.  * Algorithm :
  4.  * Order : Linear O( n )
  5.  */
  6. #include<string>
  7. using namespace std;
  8. /* min_ind contains the lowest index of s( 0 based ) which is the cyclic lex smallest */
  9. long MinCyclicShift( string s ){
  10.     s += s;
  11.     long n = s.length();
  12.     long i = 0,min_ind = 0;
  13.     while( i < n/2 ){
  14.         min_ind = i;
  15.         long j = i+1, k = i;
  16.         while( j<n && s[k] <= s[j] ){
  17.             if( s[k] < s[j] ) k = i;
  18.             else k++;
  19.             ++j;
  20.         }
  21.         while( i<=k )  i += j-k;
  22.     }
  23.     return min_ind;
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement