題目描述 將一個英文語句以單詞為單位逆序排放。例如“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;}新聞熱點
疑難解答