【题解 | 句子逆序】

句子逆序

描述

将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”

所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符

数据范围:输入的字符串长度满足 1≤n≤1000 

注意本题有多组输入

  • 输入描述:

        输入一个英文语句,每个单词用空格隔开。保证输入只包含空格和字母。

  • 输出描述:

        得到逆序的句子

下面给出一个我自己的暴力解法。。。纯暴力的那种。

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

int main() {
    cin.tie(0);
    cout.tie(0);
    ios::sync_with_stdio(false);
    string s;
    while (getline(cin, s)) {
        string a[1000];
        int j = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s[i] == ' '){
                j++;
            }
            else a[j] += s[i];
        }
        for (int i = j; i >= 0; i--) {
            cout << a[i] << " ";
        }
    }
}

这题的OJ有点问题说是多组输入,但测试组里面都是单个输入,因此下面这段代码也能跑 

#include<bits/stdc++.h>
using namespace std;

int main() {
    string str, res;
    while (cin >> str) {
        str += " " + res;
        res = str;
    }
    cout << res << endl;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值