【C语言实现】字符串旋转结果(三种方法)

字符串旋转结果

写一个函数,判断一个字符串是否为另外一个字符串旋转之后的字符串。
例如:给定s1 =AABCD和s2 = BCDAA,返回1
给定s1=abcd和s2=ACBD,返回0.

AABCD左旋一个字符得到ABCDA
AABCD左旋两个字符得到BCDAA
AABCD右旋一个字符得到DAABC

方法一

实现任意次数的左旋,然后不断进行比较。
#include<stdio.h>
#include<windows.h>
#include<assert.h>

void LeftRotate(int* str, int len, int num)
{
	assert(str);
	assert(len > 0);
	assert(num >= 0);

	num %= len;//去重,减少调用次数

	while (num != 0)
	{
		char temp = str[0];
		int i = 0;
		for (; i < len - 1; i++)
		{
			str[i] = str[i + 1];
		}
		str[i] = temp;
		num--;
	}
}

int main()
{
	char str1[] = "1234abcd";
	char str2[] = "abcd1234";
	int len = strlen(str1);
	int num = 3;
	int i = 0;
	for (; i < len; ++i)
	{
		if (strcmp(str1, str2) == 0)
		{
			printf("yes!\n");
			break;
		}
		LeftRotate(str1, len, 1);
		if (i == len)
		{
			printf("no!\n");
		}
	}
	system("pause");
	return 0;
}

方法二

划分字串,定义头指针和尾指针,运用局部逆置的方法,再整体逆置实现旋转;
第一个字串的范围[0,num-1]
第二个字串的范围[num,len-1]
总串[0-len-1]
#include<stdio.h>
#include<windows.h>
#include<assert.h>

void Reverse(char* str, int start, int end)
{
	while (start < end)
	{
		char temp = str[start];
		str[start] = str[end];
		str[end] = temp;
		start++;
		end--;
	}
}
void LeftRotate1(int* str, int len, int num)
{
	assert(str);
	assert(len > 0);
	assert(num >= 0);
	
	num %= len;

	Reverse(str, 0, num - 1);
	Reverse(str, 0, len - 1);
	Reverse(str, 0, len - 1);
}

int main()
{
	char str1[] = "1234abcd";
	char str2[] = "abcd1234";
	int len = strlen(str1);
	int num = 3;
	int i = 0;
	for (; i < len; ++i)
	{
		if (strcmp(str1, str2) == 0)
		{
			printf("yes!\n");
			break;
		}
		LeftRotate1(str1, len, 1);
		if (i == len)
		{
			printf("no!\n");
		}
	}
	system("pause");
	return 0;
}

方法三

构造双倍串,穷举所有字串,那么这个字符串里包含了任意次数的旋转情况。
#include<stdio.h>
#include<windows.h>

int main()
{
	char str1[] = "ABCDEFGH";
	char str2[] = "EFGHABCD";

	int len = strlen(str1);
	char *double_string = (char*) malloc(len * 2 + 1);

	strcpy(double_string, str1);
	strcat(double_string, str1);
	printf("double string : %s\n", double_string);

	if (strstr(double_string, str2) != NULL)
	{
		printf("Yes!\n");
	}
	else
		printf("No!n");

	free(double_string);
	
	system("pause");
	return 0;
}

延申–运用标准库函数,减少代码的编写

void *malloc( size_t size );

char *strcpy( char *strDestination, const char *strSource );

char *strcat( char *strDestination, const char *strSource );

size_t strlen( const char *string );

链接: http://cplusplus.com/.

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值