题解 | #翻转单词序列#

翻转单词序列

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

#include <algorithm>
#include <string>
class Solution {
public:
    string ReverseSentence(string str) 
    {
        if (str.empty())
        {
            return "";
        }

        int index = str.find_first_of(' ');
        int find_index = 0;
        stack<string> s;
        while (index > 0)
        {
            string tmp = str.substr(find_index, index - find_index);
            s.push(tmp);
            find_index = index + 1;
            index = str.find_first_of(' ', find_index);
        }

        //最后一个单词
        string tmp = str.substr(find_index,str.length());
        s.push(tmp);

        string str_res;
        while (!s.empty())
        {
            str_res += s.top() + ' ';
            s.pop();
        }

        //去掉最后面的空格
        str_res = str_res.substr(0, str_res.length() - 1);

        return str_res;
    }
};

全部评论

相关推荐

船长想实习:我啥技术不会决定去试试,然后进去也不干活就搅局可以吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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