题解 | #翻转单词序列#

翻转单词序列

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

  1. 绝对不要用stack.size()在弹出的时候做循环,因为它得大小是动态变化的。
#include<bits/stdc++.h>
class Solution {
public:
    string ReverseSentence(string str) {

        string res;
        if(!str.length()) return "";

        stringstream ss(str);
        stack<string> stk;

        string s;

        while(getline(ss, s,' ')){
            stk.push(s);
        }

        int size = stk.size();// 不要变pop然后这个做为size大小,必须先赋值给其他变量。

        for(int i = 0; i< size; i++){

            if(i!=size-1){
                res+= stk.top()+' ';
            }else{
                res+= stk.top();
            }

            stk.pop();
        }

        return res;
    }
};
算法解析 文章被收录于专栏

这里主要是算法岗的自我思路总结

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务