解決策:
1.2。この質問を通じて、istringstreamについて学びました。istringstreamオブジェクトは、文字列の行をバインドし、その行をスペースとして区切り文字として区切ることができます。
(1)istringstream word(s)は最初に文字列入力ストリームを作成します
(2)while(word >> w)は入力ストリームから文字列を読み取ります
class Solution {
public:
string reverseWords(string s) {
istringstream word(s);
string w;
string res;
while(word>>w) res=' '+w+res;
return res.empty()?"":string(res.begin()+1,res.end());
}
};
2. istringstreamも使用しており、各文字列をベクターに保存して、最後に接続できます
class Solution {
public:
string reverseWords(string s) {
istringstream word(s);
vector<string> vec;
string w;
string res;
while(word>>w) vec.push_back(w);
for(int i=vec.size()-1;i>=0;i--) res+=vec[i]+' ';
return res.empty()?"":string(res.begin(),res.end()-1);
}
};