clean C++ code using istringstream


  • 0
    L

    Using istringstream to read 'words' from string,the while loop don't return false until it got last word in the string.

    We need a string to store the result,the only problem we need to handle is using string.substr to remove ' ' at end of the result.

    class Solution {
    public:
        string reverseWords(string s) {
            string word;
            string ret;
            if(s.size() == 0)return ret;
            istringstream ss(s);
            while(ss>>word){
                reverse(word.begin(),word.end());
                ret = ret + word + " ";
            }
            return ret.substr(0,ret.size() - 1);
        }
    };
    

Log in to reply
 

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