An intereating solution using c++, very simple! using stl and iterator. though not fast...


  • 0
    W
    class Solution {
    public:
        void reverseWords(string &s) {
            //
        	vector<string> data;
    		string word;
    		stringstream ss(s);
    		while(ss>>word)	data.push_back(word);
    		
    		vector<string> rdata(data.rbegin(), data.rend());
    
    		s = accumulate(rdata.begin(), rdata.end(), string(""),
    			[](string s1, string s2){
    				if(s1.empty()) return s2;
    				else return s1+" "+s2; 
    			});
        }
        
    };
    

    i know it might be most efficiency, it gives another direction to solve problems. we are using c++, not pure c;
    only a container constructer and a stl function is called. have fun guys...


  • 0
    C

    Nice one, my version used an ostream_iterator instead of std::accumulate:

    using namespace std;
    
    class Solution {
    public:
        void reverseWords(string &s) {
            istringstream iss(s);
            string word;
            vector<string> vec;
    
            while (iss >> word)
                vec.push_back(word);
    
            ostringstream oss;
            copy(vec.rbegin(), vec.rend(), ostream_iterator<string>(oss, " "));
            s = oss.str();
        }
    };
    

  • 0
    W

    Yeah, your answer is more delicate ! Previously i do not known "ostringstream oss" can be used in this way "oss.str()". I have learned a new grammar rule.


  • 0
    L

    your answer is so delicate, I'll never known "ostringstring" can be used in this way if didn't find your code


  • 0
    B

    the compiler says ‘ostream_iterator’ was not declared in this scope. Did you meet this compilation error?


  • 0
    W

    Remember to add include header file iterator. Leetcode include everything for on-line judge, but we have to do it on our own computer.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.