题解 | #翻转单词序列#

翻转单词序列

http://www.nowcoder.com/practice/3194a4f4cf814f63919d0790578d51f3


class Solution {
public:
    string ReverseSentence(string str) {
        string res="";
        int k=str.length();
        if(k==0) return res;
        string tmp="";//临时变量保存每个单词
        for(int i=k-1;i>=0;--i) {
            if(str[i]!=' ') tmp=str[i]+tmp;//头插保证单词正确
            else {
                res+=tmp+' ';
                tmp="";
            }
        }
        if(tmp.length()) res+=tmp;//最后如果不是空格结尾
        return res;
    }
};


全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务