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