题目:
定义字符串的左旋转操作:把字符串前面的若干个字符移动到字符串的尾部,如把字符串abcdef左旋转2位得到字符串cdefab。
请实现字符串左旋转的函数,要求对长度为n的字符串操作的时间复杂度为O(n),空间复杂度为O(1)。
ab|cdef –> fedc|ba –>cdef|ab
#include <cassert>
#include <iostream>
using namespace std;
void swap(char *a, char *b)
{
char tmp = *a;
*a = *b;
*b = tmp;
}
void rotate_string(char *first, char *last)
{
assert(first != NULL && last != NULL);
while (first < last){
swap(first, last);
first++;
last--;
}
}
void rotate_string(char *str)
{
assert(str !=NULL);
char *first = str;
char *last = str;
while (*last != '\0'){
last++;
}
last--;
rotate_string(first, last);
}
void left_rotate_string(char *str, int pos)
{
rotate_string(str);
char *first = str;
char *last = str;
while (*last != '\0'){
last++;
}
char *mid = last;
for (int i = 0; i < pos; i++){
mid--;
}
last--;
mid--;
rotate_string(first, mid);
mid++;
rotate_string(mid, last);
}