剑指offer系列——44.翻转单词顺序列

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

    string ReverseSentence(string str) {
        if (str.empty())
            return str;
        int index1 = 0;
        int index2 = 0;
        reverse(str.begin(), str.end());
        while (index1 < str.size()) {
            while (str[index2] != ' ' && index2 < str.size())
                index2++;
            reverse(str.begin() + index1, str.begin() + index2);
            index2++;
            index1 = index2;
        }
        return str;
    }

猜你喜欢

转载自www.cnblogs.com/xym4869/p/12336362.html