Sword Pointer Offer 05. Replace spaces (Likou C++)

One: topic

Please implement a function to replace  s each space in the string with "%20".

Example 1:

Input: s = "We are happy."
 Output: "We%20are%20happy."

Two: problem-solving ideas

There is nothing to say, the only possible difficulty is to forget the traversal and go directly to the code

class Solution {
    private:
    string ret;
public:
    string replaceSpace(string s) {
        for(auto &i:s)//遍历这个string
        {
            if(i==' ')
            {
                ret+="%20";
            }
            else
            {
                ret+=i;
            }
        }
        return ret;
    }
};

It’s not possible, it’s not impossible to use push_back

class Solution {
    private:
    string ret;
public:
    string replaceSpace(string s) {
        for(auto &i:s)
        {
            if(i==' ')
            {
                ret.push_back('%');
                ret.push_back('2');
                ret.push_back('0');
            }
            else
            {
                ret.push_back(i);
            }
        }
        return ret;
    }
};

Guess you like

Origin blog.csdn.net/qq_62718027/article/details/128810061