zoukankan      html  css  js  c++  java
  • [LeetCode] Reverse Words in a String

    Reverse Words in a String

                

    Given an input string, reverse the string word by word.

    For example, Given s = "the sky is blue", return "blue is sky the".

    Clarification:
    • What constitutes a word? A sequence of non-space characters constitutes a word.
    • Could the input string contain leading or trailing spaces? Yes. However, your reversed string should not contain leading or trailing spaces.
    • How about multiple spaces between two words? Reduce them to a single space in the reversed string.

    思路:用s.substr(pos,num)把s中的子字符串取出来,存放在栈strStack中

             然后把每个子字符串从strStack中取出来组合成s;

    注意事项:

    1.s.subStr(0,0)的结果是“”,即空字符串;

    2.测试用例:

       (1)字符串首有空格、字符串末尾有空格、字符串中间有连续多个空格

       (2)空字符串

       (3)只有空格的字符串

    class Solution
    {
    public:
        void reverseWords(string &s)
        {
            if(s.size() == 0)
                return;
            string::size_type pos=0,num=0,n=0;
            stack<string> strStack;
    
            while(n < s.size())
            {
                while( n < s.size() && s[n] == ' ')
                {
                    ++n;
                }
                string::size_type num=0;
                if( n < s.size() && s[n] != ' ')     //找子字符串的初始位置pos,有可能找不到,pos=0
                {
                   pos = n;
                   ++num;
                   ++n;
                }
                while( n < s.size() && s[n] != ' ')  //计算子字符串的长度num,有可能num=0
                {
                   ++n;
                   ++num;
                }
               string subS = s.substr(pos,num); // s.substr(0,0)=""
               if(subS != "")
                   strStack.push(subS);
            }
    
        
            if(strStack.empty()) //有可能原s=“   ”(几个空格),栈中什么都没有,则s就不会从栈中得到但期望的结果是""(空字符串)。
            {
               s = "";
            }
            else
            {
              s = strStack.top();
              strStack.pop();
            }
    
            while(!strStack.empty())
            {
               s += ' ';
               s += strStack.top();
               strStack.pop();
            }
            
        }
    };
  • 相关阅读:
    给jquery 添加触屏事件,上下左右 touchwipe插件
    node.js 安装运行
    CSS3 3D 盒子模型
    javascript 获取内联样式
    HTML5 离线存储应用案例
    swipe.js 轻松实现手机端滑动效果
    手机网页轮播切换,简易版
    多行文字垂直居中
    jquery实现简单轮播
    利用media query写响应式布局
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3770954.html
Copyright © 2011-2022 走看看