Programmer interview golden classic-interview questions 01.03.URL

1. Topic introduction

URLization. Write a method to replace all spaces in the string with %20. It is assumed that there is enough space at the end of the string to store new characters, and the "real" length of the string is known. (Note: If implemented in Java, please use a character array implementation so that you can operate directly on the array.)

Example 1:

 Input: "Mr John Smith", 13
 Output: "Mr%20John%20Smith"
Example 2:

 Input: "", 5
 Output: "%20%20%20%20%20"
Prompt:

The string length is in the range of [0, 500000].

Source: LeetCode
Link: https://leetcode-cn.com/problems/string-to-url-lcci
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, problem-solving ideas

Detect spaces in the string and replace them with %20. If you use string to complete this question, as the length of the string continues to increase, when it exceeds the default space size of the string object, the redistribution and copying of storage space will cause relatively large overhead . Therefore, the method of applying for additional memory is adopted, and a fixed-length memory is dynamically applied in advance to avoid the problem of redistribution and copying of storage space.

Three, problem-solving code

方法一:
class Solution {
public:
    string replaceSpaces(string S, int length) {
        //字符串存储空间的再分配和复制开销比较大
        string str;
        for(int i = 0; i < length; ++i)
        {
            if(S[i] == ' ')
                str += "%20";
            else
                str += S[i];
        }
        return str;
    }
};

方法二:
class Solution {
public:
    string replaceSpaces(string S, int length) {
        //最大3 * length + 1
        char *arr = new char[3*length + 1];
        int j = 0;
        for(int i = 0; i < length; ++i)
        {
            if(S[i] == ' ')
            {
                arr[j++] = '%';
                arr[j++] = '2';
                arr[j++] = '0';
            }
            else
                arr[j++] = S[i];
        }
        arr[j] = '\0';
        return string(arr);
    }
};

Four, problem-solving results

Guess you like

Origin blog.csdn.net/qq_39661206/article/details/105576985