zoukankan      html  css  js  c++  java
  • 翻转单词顺序序列

    例如,“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;
    }

    天天向上
  • 相关阅读:
    [转]Spring Cloud在国内中小型公司能用起来吗?
    [转]关于maven pom.xml中dependency type 为pom的应用
    如何直接在github网站上更新你fork的repo?
    Eclipse在Tomcat环境下运行项目出现NoClassDefFoundError/ClassNotFoundException解决办法
    Jquery mobile 中在列表项上使用单选按钮
    QBus 关注并推送实时公交信息
    常用序列号
    SVN 使用锁实现独占式签出
    SQL速记
    利用交通在手数据为换乘添加关注
  • 原文地址:https://www.cnblogs.com/hg07/p/12702319.html
Copyright © 2011-2022 走看看