题目:输入一个字符串,将其进行右旋,如输入“abcdef”,右旋二个将得到"efabcd",此题有多种解法,这里介绍两种常用的
字符右旋实现:(1)三步反转法;(2)直接移动法
(1)三步反转法:1)"abcd"->"dcba";
2)"ef"->"fe"; 此时得到"dcbafe"
3)"dcbafe"->"efabcd";
(2)直接移动法:建立一个临时变量存放最后一个字符,然后将剩余所有的字符向后移动,最后将临时变量中存放的字符放入空出来的打一个位置中,如此循环n次;
(1)三步反转法
# include <stdio.h>
# include <string.h>
# include <assert.h>
void Reverse(char* start, char* end)
{
assert(start);
assert(end);
while (start < end)
{
char tmp = *start;
*start = *end;
*end = tmp;
start++;
end--;
}
}
void RightLoopMove(char* pStr, size_t n)
{
int len = strlen(pStr);
Reverse(pStr, pStr + len - n - 1);
Reverse(pStr+len-n, pStr + len - 1);
Reverse(pStr, pStr + len- 1);
}
int main()
{
char arr[] = "abcdef";
RightLoopMove(arr, 2);
printf("%s\n", arr);
system("pause");
return 0;
}
(2)直接移动法
# include <stdio.h>
# include <string.h>
# include <assert.h>
RightLoopMove(char* pStr, size_t n)
{
assert(pStr);
int len = strlen(pStr);
while (n)
{
char tmp = pStr[len-1];
for (int i = len-1; i >0; i--)
{
pStr[i] = pStr[i - 1];
}
pStr[0] = tmp;
n--;
}
}
int main()
{
char arr[] = "abcdef";
RightLoopMove(arr, 2);
printf("%s\n", arr);
system("pause");
return 0;
}
转载于:https://blog.51cto.com/10742272/1769530