例如:
ABCD左旋一个字符得到BCDA
ABCD左旋两个字符得到CDAB
方法一:一个一个移动
暴力求解法:
#include<stdio.h>
#include<string.h>
#include<assert.h>
void left_move(char* arr, int k)
{
int len = strlen(arr);
assert(arr != NULL);
assert(k <= len);
for (int i = 0;i < k;i++)
{
//左旋一个字符
char tmp = *arr;
for (int j = 0;j < len - 1;j++)
{
*(arr + j) = *(arr + j + 1);
}
*(arr + len - 1) = tmp;
}
}
int main()
{
int k;
char arr[] = "abcdef";
scanf("%d", &k);
left_move(arr, k);
printf("%s\n", arr);
return 0;
}
方法二:三步翻转法
//abcdef ba fedc cdefab
//逆序字符串的函数
#include<stdio.h>
#include<string.h>
#include<assert.h>
void reverse(char* left, char* right)
{
assert(left != NULL);
assert(right != NULL);
while (left < right)
{
char tmp = *left;
*left = *right;
*right = tmp;
left++;
right--;
}
}
void left_move(char* arr, int k)
{
int len = strlen(arr);
assert(k <= len);
assert(arr != NULL);
reverse(arr,arr+k-1);//逆序左边
reverse(arr+k,arr+len-1);//逆序右边
reverse(arr,arr+len-1);//逆序整体
}
int main()
{
int k;
char arr[] = "abcdef";
scanf("%d", &k);
left_move(arr, k);
printf("%s\n", arr);
return 0;
}