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;
    }

    天天向上
  • 相关阅读:
    为php5.6.30安装redis扩展
    Laravel利用pusher推送消息
    php闭包使用例子
    利用反射给类中方法加钩子
    mysql删除重复记录
    DB门面,查询构建器,Eloquent ORM三者的CURD
    Laravel5.1之表单验证
    服务提供者及门面
    批量搜索并替换内容
    Laravel之Elixir
  • 原文地址:https://www.cnblogs.com/hg07/p/12702319.html
Copyright © 2011-2022 走看看