题解 | #翻转单词序列#

翻转单词序列

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

#include <stack>
#include <string>
class Solution {
public:
  // 利用栈性质,一次入栈,依次出栈
  // 代码实现,注意使用string容器一些性质即可
    string ReverseSentence(string str) {
        stack<string> s;
        int i = 0;
        string tmp;
        while (str[i] != '\0') {
            for(;i < str.size(); i++)
            {
                if(str[i] != ' '){
                    // cout << str[i] <<" ";
                    tmp += str[i];
                }else{
                    ++i;
                    s.push(tmp);
                    break;
                }
            }
            if(str[i] == '\0')
            {
                s.push(tmp);
            }
            tmp.clear();
        }
        string res;
        while (!s.empty()) {
            res += s.top();
            s.pop();
            if(!s.empty()) res += ' ';// 对于最后的元素,没必要添加空格了
        }
        return res;
    }
};

挤挤刷刷! 文章被收录于专栏

记录coding过程

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务