华为机试之句子逆序

题目要求:

将一个英文语句以单词为单位逆序排放。例如“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
我的解决方案:

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

void solve(string str, vector<string> &words)
{
 string w;
 int i = 0;
 int j = str.find(" ");
 while (j != -1)
 {
  w = str.substr(i, j - i);
  words.push_back(w);
  i = j + 1;
  j = str.find(" ", i);
 }
 if (i<str.length() - 1)
 {
  w = str.substr(i);
  words.push_back(w);
 }
}

int main()
{
 //string s="I am a boy";
 string s;
 getline(cin, s);
 vector<string> words;
 //cout<<"句子中的单词分别为:"<<endl;
 solve(s, words);
 vector<string>::reverse_iterator rit;
 for (rit = words.rbegin(); rit != words.rend()-1; ++rit)
 {
  cout << *rit << ' ';
 }
 cout << *words.begin();
 cout << endl;
 return 0;

}

posted @ 2018-04-08 22:59  二十划生  阅读(183)  评论(0编辑  收藏  举报