牛客网

xiaoxiao2021-02-28  262

题目描述

对字符串中的所有单词进行倒排。

说明:

1、每个单词是以26个大写或小写英文字母构成;

2、非构成单词的字符均视为单词间隔符;

3、要求倒排后的单词间隔符以一个空格表示;如果原字符串中相邻单词间有多个间隔符时,倒排转换后也只允许出现一个空格间隔符;

4、每个单词最长20个字母;

输入描述:

输入一行以空格来分隔的句子

输出描述:

输出句子的逆序

示例1

输入

I am a student

输出

student a am I

题目地址:https://www.nowcoder.com/practice/81544a4989df4109b33c2d65037c5836?tpId=37&tqId=21254&tPage=2&rp=&ru=/ta/huawei&qru=/ta/huawei/question-ranking

思路一:初级单词逆向输出升级版,可以利用流的特性忽略空格,但是非字母都视为分隔符,首先将字符串中非字母字符全部置为空格,然后利用流特性传给临时string,push到vector中

#include <iostream> #include <string> #include <vector> #include <sstream> using namespace std; int main(){ string str = ""; while(getline(cin, str)){ vector<string> result; //非字母置为空格字符 for(char &c : str) if(!isalpha(c)) c = ' '; stringstream ss(str); string temp = ""; //利用流的特性自动避开空格 while(ss >> temp){ result.push_back(temp); } cout << result[result.size()-1]; //注意输出格式,最后一个不能再加空格 for(int i = result.size()-2; i >= 0; i--) //这里i最好是int型,size_t若size()小于2会溢出 { cout << " " << result[i]; } cout << endl; } return 0; }

转载请注明原文地址: https://www.6miu.com/read-24206.html

最新回复(0)