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();
            }
            
        }
    };
  • 相关阅读:
    我在D2讲演的视频,已经可以下载了~
    走出海量数据及访问量压力困境
    博客作者应该学习的15个国外博客
    如何将jsp动态网页转换成静态页面
    新一代网络模式Web 2.0火爆发展
    数据库设计中的14个关键技巧
    如何进行RSS推广
    运用RUP 4+1视图方法进行软件架构设计
    02java关键词变量类型
    03java运算符函数
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3770954.html
Copyright © 2011-2022 走看看