【力扣】[剑指 Offer 05.] 替换空格

一.题目

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

二.代码展示

class Solution {
public:
    string replaceSpace(string s) {
        // 原来s的下标
        int size1 = s.length() - 1;
        // 遇到空格,就在后面+=00
        for(int i = 0; i <= size1; ++i)
        {
            if(s[i] == ' ')
                s += "00";
        }

        // 算出新的下标,
        // 新的如果小于等于旧的,就说明没有空格
        int size2 =s.length() - 1;
        if(size2 <= size1)
            return s;

        // 反向遍历旧的,然后遇到空格便将20%加进去
        for(int i = size1; i >= 0; --i)
        {
            char c = s[i];
            if(c == ' ')
            {
                s[size2--] = '0';
                s[size2--] = '2';
                s[size2--] = '%';
            }
            else
                s[size2--] = c;
        }
        return s;
    }
};

上面的方法中规中矩,看看下面的代码是如何用八行解决的吧
用string创建一个新的字符串,然后将是空格的+=%20,不是空格的+=s[i]

class Solution {
public:
    string replaceSpace(string s) {
        string res ;
        for(int i = 0; i < s.size(); ++i)
        {
            if(s[i] == ' ')
                res += "%20";
            else
                res += s[i];
        }
        return res;
    }
};

你可能感兴趣的:(c++,力扣,leetcode,c++)