首页 > 学院 > 开发设计 > 正文

华为OJ:句子逆序

2019-11-08 02:15:47
字体:
来源:转载
供稿:网友

题目描述 将一个英文语句以单词为单位逆序排放。例如“I am a boy”,逆序排放后为“boy a am I” 所有单词之间用一个空格隔开,语句中除了英文字母外,不再包含其他字符

接口说明 /** * 反转句子 * * @param sentence 原句子 * @return 反转后的句子 */ public String reverse(String sentence);

输入描述: 将一个英文语句以单词为单位逆序排放。

输出描述: 得到逆序的句子

输入例子: I am a boy

输出例子: boy a am I

解答1:#include <iostream>#include <stack>#include <string>using namespace std;int main(){ string str; stack<string>s; while(cin>>str) { s.push(str); } while(!s.empty()) { cout<<s.top(); s.pop(); if(!s.empty()) cout<<' '; } return 0;}解答2:#include <iostream>#include <string>#include <sstream>using namespace std;int main(){ string s; getline(cin,s); stringstream ss(s); string res="", tmp; while (ss>>tmp) { if (res=="") res=tmp; else res=tmp+" "+res; } cout<<res; return 0;}
上一篇:关于互补滤波原理

下一篇:线段树模板

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表