字符串循环移位 - 编程珠玑的一道题

字符串循环移位 - 编程珠玑的一道题(转)
//  编程珠玑 第二章 字符串string循环移位i位
//  eg "abcdefgh" 循环移位 3位 =》 "defghabc"
#include < iostream.h >
#include 
< string .h >

char *  string_cyclicshift_v2(  char *   string int  i )
{
    
char ch;
    
int exchange;
    
int len;
    
    exchange 
= 0;
    len 
= strlen( string );
    
    i 
= i%len;
    
if ( 0 == i )
        
return string;
    
    
int start_pos=0;
    
while ( exchange<len )
    
{
        
char ch = string[start_pos];
        
        
int currpos = start_pos;
        
int nextpos = (len+currpos+i)%len;
        
while ( nextpos != start_pos )
        
{
            
string[currpos] = string[nextpos];
            
++exchange;
            
            currpos 
= nextpos;
            nextpos 
= (len+currpos+i)%len;

        }

         cout
<<string<<endl;
        
string[currpos] = ch;
        
++exchange;
        
        
++start_pos;
    }

    
    
return string;
}


int  main() {
    
char string[7]={'a','b','h','d','h','s'};
    cout
<<string<<endl;
    
char* s;
    s
=string_cyclicshift_v2(string,4);
    cout
<<s<<endl;

return 0;
}

要求时间复杂度空间复杂度都尽可能的低。

时间复杂度 O(n), 空间复杂度O(1),常量时间。

http://blog.csdn.net/zdl1016/archive/2009/09/21/4575309.aspx

你可能感兴趣的:(字符串循环移位 - 编程珠玑的一道题)