zoukankan      html  css  js  c++  java
  • 翻转字符串(坑比较多)

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

    Example 1:

    Input: "the sky is blue"
    Output: "blue is sky the"
    

    Example 2:

    Input: "  hello world!  "
    Output: "world! hello"
    Explanation: Your reversed string should not contain leading or trailing spaces.
    

    Example 3:

    Input: "a good   example"
    Output: "example good a"
    Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

    class Solution {
    public:
        //去掉多余的空格
         string reverseWords(string s) {
            int i=0;
            while(s[i] == ' ') s.erase(s.begin());
            reverse(s.begin(),s.end());
            i=0;
            while(s[i] == ' ') s.erase(s.begin());
            //翻转
            int j=0;
            cout<<s<<endl;
            for(i=0;i<s.size();i++){
                if(s[i] == ' '){
                    reverse(s.begin()+j,s.begin()+i);
                    i++;
                    while(s[i] == ' ')  s.erase(s.begin()+i);
                    j = i;
                }
            }
            //最后一个  reverse第二个参数是翻转的位置的后一个位置,所以单独考虑
            reverse(s.begin()+j,s.end());
            return s;
        }
    

      

  • 相关阅读:
    FastAdmin Shopro商城安装
    MYSQL ERROR 10060
    宝塔命令
    kdevtmpfsi挖矿病毒处理
    VUE安装
    原生JS请求(AJAX)
    Bootstrap: 模态框组件
    Bootstrap: 缩略图组件
    Bootstrap: 栅格系统
    Bootstrap: 下拉菜单组件 & 分页组件
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/13622642.html
Copyright © 2011-2022 走看看