Cattle off network - to prove safety office- Flip word order of the columns

Title: Cattle recently came off a new employee Fish, every morning and always will be holding a magazine in English, write some sentences in the book. Cat Fish wrote to colleagues interested in the content, look to the day he borrowed Fish, but not read its meaning. For example, "student. A am I" . Later I realized that this guy had the sentence word order reversed, the correct sentence should be "I am a student.". Cat on the order of every one of these words do not flip the line, can you help him?
Ideas: first flip each word, and then flip the whole sentence.

class Solution {
public:
    string ReverseSentence(string str) {
        int length =str.size();
        if (str.size()==0) return "";
        str+=' ';
        int m =0;
        for(int i=0;i<length+1;++i)
        {
            if(str[i]==' ')
            {
                reverseword(str,m,i-1);
                m=i+1;
            }
        }
        str =str.substr(0,length);
        reverseword(str,0,length-1);
        return str;
    }
    void reverseword(string &str,int l,int r)
    {
        while(l<r)
        {
            swap(str[l],str[r]);
            ++l,--r;
        }
    }
};

Guess you like

Origin blog.csdn.net/qq_43387999/article/details/91351335