翻转单词顺序列

原文地址:https://www.jianshu.com/p/113cd20b3db1

时间限制:1秒 空间限制:32768K

题目描述

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

我的代码

class Solution {
public:
    string ReverseSentence(string str) {
        int n=str.size();
        if(n<2)
            return str;
        string res="",tmp="";
        for(int i=0;i<n;i++){
            if(str[i]==' '){
                res=" "+tmp+res;
                tmp="";
            }
            else
                tmp+=str[i];
        }
        if(tmp!="")
            res=tmp+res;
        return res;
    }
};

运行时间:3ms
占用内存:472k

原文地址:https://www.cnblogs.com/cherrychenlee/p/10822468.html