void left_move1(char* arr)
{
assert(arr);
int n = 0;
int i = 0;
int len = strlen(arr);
printf("请输入左旋转位数:");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
char tmp = *arr;//拿出首元素
int k = 0;
for(k = 0; k < len - 1;k++)//len-1 防止arr[j+1]越界访问
{
arr[k] = arr[k+1];//完成其他元素前移
}
*(arr + len - 1) = tmp;//第一个元素放到最后
}
}
void reverse(char* left, char* right)//逆序
{
assert(left != NULL);
assert(right != NULL);
while (left < right)
{
int tmp = *(left);
*(left) = *(right);
*(right) = tmp;
left++;
right--;
}
}
void left_move2(char* arr)
{
assert(arr);
int len = strlen(arr);
int n = 0;
printf("请输入左旋转位数:");
scanf("%d", &n);
n = n % len;//防止左旋位数大于字符串,导致重复计算
reverse(arr,arr+n-1);//逆序左边n位
reverse(arr+n,arr+len-1);//逆序右边
reverse(arr,arr+len-1);//逆序整体
}
int main()
{
char arr[] = "abcdef";
left_move1(arr);//字符串左旋转 方案一
left_move2(arr);//方案二
printf("%s\n", arr);
return 0;
}
//判断arr2是否为arr1 左旋转得到的
void reverse(char* left, char* right)//逆序
{
assert(left != NULL);
assert(right != NULL);
while (left < right)
{
int tmp = *(left);
*(left) = *(right);
*(right) = tmp;
left++;
right--;
}
}
void left_move2(char* arr)
{
assert(arr);
int len = strlen(arr);
reverse(arr,arr+1);//逆序左边1位
reverse(arr+2,arr+len-1);//逆序右边
reverse(arr,arr+len-1);//逆序整体
}
//方案一
int is_left_move1(char* arr1, char* arr2)//穷举法
{
int len = strlen(arr1);
int i = 0;
for (i = 0; i < len; i++)
{
if (strcmp(arr1, arr2) == 0)//先判断是否相同
{
return 1;
}
else
left_move2(arr1);//不相同字符串则左移一次
}
return 0;
}
//方案二
int is_left_move2(char* arr1, char* arr2)
{
int len1 = strlen(arr1);
int len2 = strlen(arr2);
if (len1 != len2)
return 0;
//int i = 0;
//for (i = 0; i < len1; i++)//arr1字符串中追加一个arr1字符串
//{
// char tmp = *(arr1 + i);
// *(arr1 + i) = *(arr1 + len1 + i);
// *(arr1 + len1 + i) = tmp;
//}
//strcat(arr1, arr2);//字符串追加字符串a字符串追加b字符串
strncat(arr1, arr1, len1);//字符串追加字符串 a字符串追加a字符串
char * ret = strstr(arr1, arr2);//判断是否是其子字符串
if (ret == NULL)
{
return 0;
}
else
return 1;
}
int main()
{
char arr1[30] = "cdefba";
char arr2[] = "cdefba";
//int ret = is_left_move1(arr1, arr2);
int ret = is_left_move2(arr1, arr2);
if (ret == 1)
printf("yes");
if (ret == 0)
printf("no");
return 0;
}