翻转单词顺序序列

例如,“student. a am I”。应该是“I am a student.”

// ConsoleApplication3.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include "string"
using namespace std;
#include<stack>

class Solution
{
public:

    string reverseWords(string str)
    {
        if (str.empty())
        {
            return "";
        }
        string strTemp = "";
        stack<string> node;
        for (char s : str)
        {
            // 如果当前字符不为空或结束字符
            if (s != '' && s != ' ')
            {
                // 则将当前字符加入当前临时单词中
                strTemp = strTemp + s;
            }
            else
            {
                // 如果当前字符为空,
                // 且当前临时单词字符串大小不为0,
                // 则表示当前临时单词字符串对应的单词拼接完成
                if (strTemp.size() !=0)
                {
                    node.push(strTemp);
                }
                // 重置当前临时单词字符串
                strTemp.clear();
            }
        }

        // 将字符串最后的单词入栈  最后没有空格、这里剩下最后一个student
        // 上面走完后、没有走入栈
        if (strTemp.size() != 0)
        {
            node.push(strTemp);
        }

        //出栈
        string strRet = "";
        while (!node.empty())
        {
            strRet += node.top() + ' ';
            node.pop();
        }

        //去掉最后的空格
        strRet = strRet.substr(0, strRet.size() - 1);
        return strRet;
    }

    Solution();
    ~Solution();

private:

};

Solution::Solution()
{
}

Solution::~Solution()
{
}


int main()
{
    Solution solu;
    string strRet = "";
    strRet= solu.reverseWords("i am a student");
    return 0 ? strRet.size() > 0:-1;
}

天天向上
原文地址:https://www.cnblogs.com/hg07/p/12702319.html