// 編程珠璣 第二章 字符串string循環(huán)移位i位
// eg "abcdefgh" 循環(huán)移位 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;}

要求時間復(fù)雜度空間復(fù)雜度都盡可能的低。
時間復(fù)雜度 O(n), 空間復(fù)雜度O(1),常量時間。
http://blog.csdn.net/zdl1016/archive/2009/09/21/4575309.aspx

