定義字符串的左旋轉操作:把字符串前面的若干個字符移動到字符串的尾部。
如把字符串abcdef左旋轉2位得到字符串cdefab。請實現字符串左旋轉的函數。
要求時間對長度爲n的字符串操作的複雜度爲O(n),輔助內存爲O(1)。
LeftRotateStr(char *str, unsigned int k)
split str to two part
//one part is 0-k-1,another is k-n-1
reverse two part of the str
reverse the str with two reversed part
C++實現
char * LeftRotateStr(char *str, unsigned int k)
{
if(str != NULL)
{
//split str to two part
int len = static_cast<int>(strlen(str));
char *firstStrStart = str;
char *firstStrEnd = str+k-1;
char *secondStrStart = str+k;
char *secondStrEnd = str+len-1;
//reverse two part of the str
ReverseStr(firstStrStart,firstStrEnd);
ReverseStr(secondStrStart, secondStrEnd);
//reverse the str with two reversed part
ReverseStr(firstStrStart, secondStrEnd);
}
return str;
}