Reverse Words in a String III - C++ solution - single traversal


  • 0
    S

    Idea is to keep adding characters at the begin index and the begin index is updated each time we read a 'SPACE' character. Would like to get feedback on the below solution.

        string reverseWords(string s) {
            std::string output;
            std::string::size_type i, remember, strsize = s.size();
            for (i = 0, remember = 0; i < strsize; i++) {
                if (s[i] == ' ') {
                    output.append(" ");
                    remember = i+1;
                }
                else {
                    output.insert(remember, 1, s[i]);
                }
            }
            return output;
        }
    

Log in to reply
 

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