说明:转载请注明出处http://blog.csdn.net/yuanwei1314/article/details/40735935
题目:给定一个字符串,要求把字符串前面的若干个字符移动到字符串的尾部,如把字符串“abcdef”前面的2个字符'a'和'b'移动到字符串的尾部,使得原字符串变成字符串“cdefab”。请写一个函数完成此功能,要求对长度为n的字符串操作的时间复杂度为 O(n),空间复杂度为 O(1)。
思路:按照常规思路每次移动一个字符,这样如果移动k个字符则时间复杂度为O(k*n)。题目要求时间复杂度为 O(n),不符合要求,只能寻求其他办法。我们把字符串S=AB分两个部分,其中A为需要移动的那部分。举例:这里S="abcedef",则A="ab",B="cdef"。从数学上可以知道,要达到上面的要求需要把B和A分别转置即可。
具体做法则反其道而行之,将A和B先转置,再整个转置则得到最终的结果。即:这就是我们要得到的最后的结果。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*反转字符串*/
void reverse(char *s, int low, int high)
{
int i;
char tmp;
while (low < high)
{
tmp = *(s+high);
*(s+high) = *(s+low);
*(s+low) = tmp;
low++;
high--;
}
}
/*反转字符串*/
void rotateString(char *s, int n, int m)
{
m %= n;
reverse(s, 0, m-1);
reverse(s, m, n-1);
reverse(s, 0, n-1);
}
int main()
{
char s[] = "abcdefg";
rotateString(s, strlen(s), 3);
printf("%s\n", s);
return 0;
}