描述
将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I”
所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符
数据范围:输入的字符串长度满足 1 \le n \le 1000 \1≤n≤1000
注意本题有多组输入
输入描述:
输入一个英文语句,每个单词用空格隔开。保证输入只包含空格和字母。
输出描述:
得到逆序的句子
示例1
输入:
I am a boy
复制输出:
boy a am I
复制
示例2
输入:
nowcoder
复制输出:
nowcoder
用了很笨的方法,占内存比较大500kb。
欢迎优化~
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
using namespace std;
int main() {
bool flag = false;
string s;
string s1;
getline(cin,s);
vector<string>result;
for (int i = 0; i <( s.length()); i++)
{
if (s[i] == ' ')
{
flag = true;
result.push_back(s1);
s1 = "";
}
else
{
s1 += s[i];
}
}
if (flag)
{
cout << s1<<" ";
vector<string>::reverse_iterator pos;
for (pos = result.rbegin(); pos != result.rend(); pos++)
cout << *pos<<" ";
cout << endl;
}
else
{
reverse(s1.begin(), s1.end());
cout << s1 << endl;
}
return 0;
}
下面的解法是大神的,400kb。唉,忘接了栈
#include<bits/stdc++.h>
using namespace std;
stack<string> s;
int main(){
string str;
while(cin>>str){
s.push(str);
}
while(!s.empty()){
cout<<s.top()<<" ";
s.pop();
}
return 0;
}