My concise O(n) time and O(1) solution. Any advice?


  • 0
    A

    The trick is using getline to deal with space characters. However the insert function is a little bit slow.
    BTW: I run the code several time with different time consuming...sometimes it's 32ms, usually 11-13ms, is it because of a network delay?

     void reverseWords(string &s) {
            string word;
            int len = s.length();
            stringstream ss(s);
            while(getline(ss, word, ' ')){
                if(word.length() > 0){  
                    word = " " + word;
                    s.insert(len, word);
                }
            }
            s.erase(0, len+1);
        }
    

    an alternative O(n) space solution seems faster...

    void reverseWords(string &s) {
            string word, ret = "";
            stringstream ss(s);
            while(getline(ss, word, ' ')){
                if(word.length() > 0)
                    ret = word + " " + ret;
            }
            s = ret.substr(0, ret.length()-1);
        }
    

    any advice?


Log in to reply
 

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