剑指offer 面试题42 翻转单词顺序 | 左旋转字符串

本文介绍了一种使用C++实现字符串反转及左旋的方法。通过定义两个函数ReverseSentence和LeftRotate,可以实现句子中单词的反转以及字符串的左旋操作。代码示例展示了如何使用这些函数处理字符串。

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


#include <iostream>
#include <cstring>
using namespace std;
void Reverse(char* str,int start,int end){
	if(!str) return;
	for(int i=start,j=end;i<j;++i,--j){
		char tmp=str[i];
		str[i]=str[j];
		str[j]=tmp;
	}
}
char* ReverseSentence(char* str){
	if(!str) return NULL;
	int len=strlen(str);
	//reverse every char
	Reverse(str,0,len-1);
	//fix every word based on ' '
	int start=0,end=0;
	while(end<len){
		while(str[end]!=' '){
			if(str[end]=='\0')
				break;
			end++;
		}
		Reverse(str,start,end-1);
		start=++end;
	}
	//fix the last word
	Reverse(str,start,end-1);
	return str;	
}
char* LeftRotate(char* str,int n){
	if(!str||n<=0) return NULL;
	int len=strlen(str);
	int start=0,end=len-1;
	//reverse the whole string
	Reverse(str,start,end);
	//fix the left part
	Reverse(str,start,len-n-1);
	//fix the right part
	Reverse(str,len-n,end);
	return str;
}
int main(){
	char str[]={"he is a student. "};
	char str2[]={"asdfghj"};
	cout<<ReverseSentence(str)<<endl;
	cout<<LeftRotate(str2,3)<<endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值