要求将一个字符串向右平移n位,溢出的字符放在字符串的左边.
给出一个字符串“abcdef”,要求向右偏移n位,并将超过右边的数放到字符串的左边.
如果用暴力的方法,每次移动的需要处理string_length次,总的时间复杂度为O(mn).
现在有一种较为巧妙的方法,时间复杂度为O(n).
首先将需要移动的部分和不进行移动的分为两个部分,对两个部分分别进行翻转,然后再对整体翻转.
其中左边要进行翻转部分的长度为string_length%n.
代码
#include<stdio.h>
#include<string.h>
char test[100];
int rotate_string(int left,int right)
{
while(left < right)
{
char temp = test[left];
test[left] = test[right];
test[right] = temp;
left++;
right--;
}
}
int main()
{
gets(test);
printf("Input the n of rotating:");
int n;
scanf("%d",&n);
int m = n % strlen(test);
rotate_string(0,m-1);
rotate_string(m,strlen(test)-1);
rotate_string(0,strlen(test)-1);
puts(test);
return 0;
}