循环移位

本文介绍了如何使用C语言实现字符串的循环移位操作,包括算法的时间和空间复杂度分析,以及具体实现步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目要求:

将字符串str进行循环移位,要求算法空间复杂度O(1),时间复杂度O(n)

思路:

假设str需要循环移位k位,则将其分为前后两部分,分别长k和n-k,称AB

则循环移位的过程即为XY->YX. 可由XT即转置完成,(XTYT)T=(YT)T(XT)T=YX


实现如下:

#include"stdio.h"
#include"string.h"

void ReverseString(char* str, unsigned int nStart, unsigned int nEnd)
{
	char tmp;
	while(nStart < nEnd)
	{
		tmp = str[nStart];
		str[nStart] = str[nEnd];
		str[nEnd] = tmp;
		++ nStart;
		-- nEnd;
	}
}

void RightReverse(char* str, unsigned int nBit, unsigned int nLen)
{
	//avoid exception
	if (nBit > 0 && nLen > 0)
	{	
		ReverseString(str, 0, nLen - 1);

		ReverseString(str, 0, nBit - 1);
		ReverseString(str, nBit, nLen - 1);
		
			
	}	
}

void LeftReverse(char* str, unsigned int nBit, unsigned int nLen)
{
	//avoid exception
	if (nBit > 0 && nLen > 0)
	{	
		ReverseString(str, 0, nBit - 1);
		ReverseString(str, nBit, nLen - 1);
	
		ReverseString(str, 0, nLen - 1);
	}	
}

int main()
{
	const int MAXLEN = 64;
	char str[MAXLEN] = {0};
	unsigned int kBit, len;

	printf("Please input the string and start from the bit:");
	while (scanf("%s%d", str, &kBit) != EOF)
	{
		len = strlen(str);

		if (kBit > len)
			kBit %= len;

		RightReverse(str, kBit, len);
		LeftReverse(str, kBit, len);

		printf("%s\n",str);
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值