试解leetcode算法题--翻转字符串里的单词

<题目描述>
给定一个字符串,逐个翻转字符串中的每个单词。
示例: 输入: “the sky is blue”, 输出: “blue is sky the”.

<原题链接>
https://leetcode-cn.com/problems/reverse-words-in-a-string

<理明思路>
既然是要反向输出,那么先进后出的原则自然就先想到了栈,我们可以将核心算法简单列举:
1】将元素赋值给栈;
2】将栈元素赋值给字符串;
3】返回。
然后先写核心算法的代码,核心算法无误后再考虑空格和其它的特殊情况即可。

<样例代码>

给代码前先多说一句。。。如果在提交的时候无论如何修改都会频繁出现例如下面的错误或是莫名出现了“the sky is blue”的输出,
《试解leetcode算法题--翻转字符串里的单词》
那是因为原题给的基本代码可能是有问题的。。。
《试解leetcode算法题--翻转字符串里的单词》
解决方法是把题目给的void型改成string类型,并且将最终结果作为string型返回即可。
好了,下面可以放代码了:

#include<iostream>
#include<stack>
#include<string.h>
using namespace std;
class Solution {
public:
    string reverseWords(string &s) {  //原题给的void型,这里改为string型并设置了相应的返回值。
        stack<string> str;
        string s0 = "";
        if(s.empty())
        {
            s = "";
            return s;
        }
        for(int i=0;i<s.length();i++)
        {
            if(s[i]!=32)
            {
                s0+=s[i];
                continue;
            }  //得到字符组成字符串。
            else if(!s0.empty())
            {
                str.push(s0);  //字符串入栈。
                s0.clear();    //这里、还有下面都要注意及时清空字串。
            }
        }
        if(!s0.empty())
        {
            str.push(s0);
            s0.clear();
        }
        while(!str.empty())
        {
            s0+=str.top();   //取值、并出栈。
            str.pop();
            s0+=" ";
        }
        if(s0.empty())
        {
            s = "";
            return s;
        }
        s0.erase(s0.end()-1);
        s = s0;
        return s;
    }
};
//日常省略main函数。
    原文作者:miko2018
    原文地址: https://blog.csdn.net/miko2018/article/details/81809820
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞