翻转单词顺序列

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

class Solution {
public:
    string ReverseSentence(string str) {
        string res = "";
        int count = 0;
        for(int i = str.length()-1;i >= 0;--i)
            {
            if(str[i] != ' ')
                {
                count++;
            }
            else if(str[i] == ' ')
                {
                res += str.substr(i + 1,count);
                res += ' ';
                count = 0;
            }
            if(i == 0)
                res += str.substr(i,count);
            
        }
        return res;
        
        
    }
};

主要用到了res.substr(m,n)这个函数,表示返回res字符串的从下标m起n个字符的子串。

posted @ 2016-10-17 20:44  mximo  阅读(134)  评论(0编辑  收藏  举报