151翻转字符串里的单词(暴力、istringstream)

1、题目描述

给定一个字符串,逐个翻转字符串中的每个单词。

说明:

  • 无空格字符构成一个单词。
  • 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
  • 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。

2、示例

输入: "the sky is blue"
输出: "blue is sky the"

3、题解

解法一:暴力

基本思想:暴力法

  • s的第一个单词前面填补一个空格,使得翻转后第一个单词与第二个单词间存在空格
  • 从后往前遍历字符串s,遇到单词,将空格+该单词拼接到res,使得每个单词间存在空格

解法二:用stringstream做

#include<iostream>
#include<algorithm>
#include<vector>
#include<sstream>
using namespace std;
class Solution {
public:
	string reverseWords(string s) {
		//基本思想:暴力法
		//s的第一个单词前面填补一个空格,使得翻转后第一个单词与第二个单词间存在空格
		if (s[0] != ' ')
			s.insert(0, 1, ' ');
		string res;
		int i = s.size() - 1, pos;
		//从后往前遍历字符串s
		while (i >= 0)
		{
			//遇到单词,将空格+该单词拼接到res,使得每个单词间存在空格
			if (s[i] != ' ')
			{
				pos = i;
				while (i >= 0 && s[i] != ' ')
					i--;
				res += s.substr(i, pos - i + 1);
			}
			i--;
		}
		//去掉多的一个空格
		if (res[0] == ' ')
			res.erase(0, 1);
		return res;
	}
};
class Solution1 {
public:
	string reverseWords(string s) {
		//基本思想:用stringstream做
		istringstream words(s);    //words保存s的一个拷贝
		string res, word;
		//从流words中读取单词
		while (words >> word)
		{
			res = " " + word + res;
		}
		//去掉多的一个空格
		if (res[0] == ' ')
			res.erase(0, 1);
		return res;
	}
};
int main()
{
	Solution1 solute;
	string s = "the sky is blue";
	cout << solute.reverseWords(s) << endl;
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值