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

来源:互联网 发布:买情趣 淘宝 编辑:程序博客网 时间:2024/05/16 10:13

题目描述

将一个英文语句以单词为单位逆序排放。例如“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;elsecout << *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;}