牛客网_华为机试_013_句子逆序

63 篇文章 1 订阅
28 篇文章 0 订阅

题目描述

将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”
所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符


接口说明

/**
 * 反转句子
 * 
 * @param sentence 原句子
 * @return 反转后的句子
 */
public String reverse(String sentence);

 

 

 


输入描述:

将一个英文语句以单词为单位逆序排放。



输出描述:

得到逆序的句子

示例1

输入

I am a boy

输出

boy a am I

题目地址:https://www.nowcoder.com/practice/48b3cb4e3c694d9da5526e6255bb73c3?tpId=37&tqId=21236&tPage=1&rp=&ru=%2Fta%2Fhuawei&qru=%2Fta%2Fhuawei%2Fquestion-ranking

思路一:笨办法。将单词分割存入vector,然后逆序输出 1ms

#include <stack>
#include <string>
#include <iostream>
using namespace std;.
int main()
{
	string str = "";
	while (getline(cin, str))
	{
		vector<string> result;
		int index = str.find(" ");
		while (index != string::npos)
		{
			result.push_back(str.substr(0, index));
			str = str.substr(index + 1);
			index = str.find(" ");
		}
		result.push_back(str);
		for (auto rit = result.crbegin(); rit != result.crend(); ++rit)
		{
			if (rit == result.crend() - 1)
				cout << *rit;
			else
				cout << *rit << " ";
		}
		cout << endl;

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

思路二:后进先出,stack的特性,利用STL的stack实现 1ms

#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
   stack<string> stackStr;
	string str = "";
	while(cin >> str)
	{
		stackStr.push(str);
	}
	while (!stackStr.empty())
	{
		cout << stackStr.top();
		stackStr.pop();
		if (!stackStr.empty())
			cout << " ";
	}
	cout << endl;
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值