題目描述
牛客最近來了一個新員工Fish,每天早晨總是會拿着一本英文雜誌,寫些句子在本子上。同事Cat對Fish寫的內容頗感興趣,有一天他向Fish借來翻看,但卻讀不懂它的意思。例如,“student. a am I”。後來才意識到,這傢伙原來把句子單詞的順序翻轉了,正確的句子應該是“I am a student.”。Cat對一一的翻轉這些單詞順序可不在行,你能幫助他麼?
題解
#include <iostream>
#include <string>
using namespace std;
string ReverseSentence(string str) {
string res = "", temp = "";
for (int i = 0; i < str.length(); i++) {
if (str[i] == ' ') {
res = " " + temp + res;
temp = "";
} else temp += str[i];
}
res = temp + res;
return res;
}
int main() {
ios::sync_with_stdio(false);
string s;
getline(cin, s);
cout << ReverseSentence(s);
return 0;
}