151. Reverse Words in a String & 186.Reverse Words in a String II & 翻转单词顺序列

来源:互联网 发布:mac os x10.10raid 编辑:程序博客网 时间:2024/06/05 09:24

题目描述

牛客最近来了一个新员工Fish,每天早晨总是会拿着一本英文杂志,写些句子在本子上。同事Cat对Fish写的内容颇感兴趣,有一天他向Fish借来翻看,但却读不懂它的意思。例如,“student. a am I”。后来才意识到,这家伙原来把句子单词的顺序翻转了,正确的句子应该是“I am a student.”。Cat对一一的翻转这些单词顺序可不在行,你能帮助他么?

解答

我们使用wi来表示第i个单词,用wi’表示翻转后的单词。注意,当将一个单词翻转两次后,可以得到原始的单词,即(wi’)’=wi。
输入的字符串是w1w2…wn。如果我们翻转整个字符串,我们将得到wn’…w2’w1’。然后我们将单词逐个翻转,就可以得到wn…w2w1。

class Solution {public:    void reverseWords(string &s) {        int length = s.length();        reverse(s.begin(),s.end());        int read = 0;        int write = 0;        while(read < length)        {            //skip leading white space and more than one white spaces between words            if(s[read] == ' ')                ++read;            else            {                //record the start of a word                int wordStart = read;                //count the length of a word                while(read < length && s[read] != ' ')                    ++read;                //reverse  current word                 reverse(s.begin() + wordStart,s.begin() + read);                //copy current word to the appropriate position                copy(s.begin() + wordStart,s.begin() + read,s.begin() + write);                //move write to the end of current word                write += read - wordStart;                //add white space between words                if(write < length)                    s[write] = ' ';                //move write one step forward                   ++write;            }        }        //s is not a empty string or string of white spaces       if (write)        {            s = s.substr(0,write-1);        }        else            s = "";    }};
0 0