• 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".

    click to show clarification.

    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.
    些麻烦了,懒得改。对于空格,只要while就能解决。
    注意,string 和 char *是不一样的。
     
    class Solution {
    public:
        void reverseWords(string &s) {
            stack<string> sk;
            if(s.size()==0)return ;
            int i = 0;
            int b = 0,e = 0;
            if(s.size()==1)
            {
                if(s[0] == ' ')
                {
                    s = "";
                    return;
                }
                else return;
            }
            for(i = 0 ; i < s.size()-1;i++)
            {
                if(s[i] == ' '&&s[i+1] != ' ')
                {
                    b = i+1;
                }
                else if(s[i] != ' ' && s[i+1] == ' ')
                {
                    e = i+1;
                    string tp = s.substr(b,e-b);
                    sk.push(tp);
                }
            }
            if(s[s.size()-1] != ' ')
            {
                string tp = s.substr(b,s.size());
              //  if(b != e)
                {
                    sk.push(tp);
                }
            }
            
            if(sk.empty())
            {
                s="";
                return;
            }
            s = sk.top();
            sk.pop();
            
            while(!sk.empty())
            {
                string tp = sk.top();
                s = s + ' '+tp;
                sk.pop();
            }
            //s = s+'';
        }
    };
    

      

  • 相关阅读:
    Magento:Paypal付款不成功返回后不要清空购物车产品的解决方案
    magento设置订单状态
    linux下查看所有用户以及用户组
    网站无法访问的原因
    magento 多域名多店铺
    linode空间lamp环境的搭建
    hp p410固件更新
    tracert
    镜像架设
    nohup
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3621118.html
Copyright © 2020-2023  润新知