• [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();
            }
            
        }
    };
  • 相关阅读:
    SharePoint 2013 配置基于表单的身份认证
    SharePoint 2013 场解决方案包含第三方程序集
    SharePoint 2010 站点附加数据升级到SP2013
    SharePoint 2013 在母版页中插入WebPart
    SharePoint 2013 搭建负载均衡(NLB)
    SharePoint 部署解决方案Feature ID冲突
    SharePoint 2013 配置基于AD的Form认证
    SharePoint Server 2016 Update
    SharePoint 2013 为用户组自定义EventReceiver
    SharePoint 2013 JavaScript API 记录
  • 原文地址:https://www.cnblogs.com/Xylophone/p/3770954.html
Copyright © 2020-2023  润新知