[每日一题]45:倒置字符串

122 篇文章 36 订阅
51 篇文章 0 订阅

题目描述

将一句话的单词进行倒置,标点不倒置。比如 I like beijing. 经过函数后变为:beijing. like I

输入描述:

每个测试输入包含1个测试用例: I like beijing. 输入用例长度不超过100

输出描述:

依次输出倒置之后的字符串,以空格分割

示例1:

输入
I like beijing.
输出
beijing. like I
思路1:
  1. 先将整个字符串逆置过来,

  2. 遍历字符串,找出每个单词,对单词逆置。

这里我们可以使用了stl算法中的 reverse

解答代码1:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
	string str;
	getline(cin, str);	// 注意这里要使用getline,cin>>s遇到空格就接收结束了

	// 翻转整个句子 
	int start = 0;
	int end = str.size() - 1;
	for (start = 0; start < end; start++, end--) {
		swap(str[start], str[end]);
	}

	// 翻转每个单词
	end = 0;
	while (end != str.size()) {
		start = end;
		while (str[end] != ' ' && end != str.size()) {
			end++;
		}

		//找到空格
		int tmp;
		if (end != str.size()) {
			tmp = end + 1;
		}
		else {
			tmp = end;
		}
		
		--end;
		for (; start < end; start++, end--) {
			swap(str[start], str[end]);
		}
		end = tmp;
	}
	
	cout << str << endl;

	return 0;
}

代码2

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main() {
	string s;
	// 注意这里要使用getline,cin>>s遇到空格就接收结束了 
	getline(cin, s);
	// 翻转整个句子 
	reverse(s.begin(), s.end());
	// 翻转单词
	auto start = s.begin();
	while (start != s.end()) {
		auto end = start;
		while (end != s.end() && *end != ' ')
			end++;
		reverse(start, end);
		if (end != s.end())
			start = end + 1;
		else
			start = end;
	}
	cout << s << endl;

	return 0;
}
思路2

第二思路是一个比较讨巧的思路,直接利用cin>>s接收输入,遇到空格就结束了,自然就分割开了每个单词,其次将每次接收到的单词拼接到之前串的前面就逆置过来了

题解代码:

#include <iostream>
#include <string>
using namespace std;

// cin读取string时自动会被空格分隔开,用另一个字符串存储进行逆序输出 
int main()
{
    string s1, s2;
    cin >> s2;
    while (cin >> s1)
        s2 = s1  + " " + s2;
    cout << s2 << endl;
    return 0;
}

如有不同见解,欢迎留言讨论~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值