Swordはオファー151を指します。文字列[medium] -istringstreamの単語を反転します

解決策:

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);
    }
};

 

オリジナルの記事を65件公開 いいね1 訪問数495

おすすめ

転載: blog.csdn.net/qq_41041762/article/details/105431668