Code Capriccio - String - Sword Pointer Offer 05. Replace spaces

Sword Points Offer 05. Replace spaces

This section corresponds to the Code Random Record: Code Random Record , explanation video: None yet

exercise

Question link: Sword refers to Offer 05. Replace spaces - LeetCode

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

示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."

Create a new string to save the result

The question is not difficult, but it is not easy to write a good solution. First, let’s talk about conventional thinking.

Create a new string res to save the result, traverse the array, when a space is encountered, let it res+=%20, otherwise let res + the original character

class Solution {
    
    
   public:
    string replaceSpace(string s) {
    
    
        string res = "";
        for (int i = 0; i < s.length(); i++) {
    
    
            if (s[i] == ' ') {
    
    
                res += "%20";
            } else {
    
    
                res += s[i];
            }
        }
        return res;
    }
};
  • Time complexity: O( nnn ). where n is the length of the input string s. Because there is a loop in the code that iterates through the entire input string once, the time complexity is proportional to n
  • Space complexity: O( nnn ). In the worst case, the length of the output string res will be three times that of the input string s, that is, when every character in s is a space, 3n extra space is needed to store the result

replace function

The replace function of C++ does not have the usage in languages ​​​​such as Java. It return s.replace(" ","%20");can be used directly

The replace function in C++ has three parameters: the starting position of the replacement, the number of characters to be replaced, and the new string in the replacement area. Then we only need to traverse the string once, and when encountering a space, replace the current position %20with

class Solution {
    
    
   public:
    string replaceSpace(string s) {
    
    
        for (int i = 0; i < s.length(); i++) {
    
    
            if (s[i] == ' ') {
    
    
                s.replace(i, 1, "%20");
            }
        }
        return s;
    }
};
  • Time complexity: O( n 2 n^2n2 ). Each time the function is calledreplace(), the characters behind the entire string need to be moved backwards to make room for the new characters. Therefore, in the worst case, when every character in the input string is a space, usingreplace()the function will replace the i-th character with "%20", all characters after i must be moved backwards Move, which requires O(n) time complexity. Since this operation needs to be performed n times, the total time complexity is O(n^2)
  • Space complexity: O( 1 11 ). Only constant level extra space is used. Althoughreplace()the length of the string increases each time the function is called, the final string returned is still the original strings, so no additional space is required to store the result.

double pointer

The more recommended solution to this problem is the double pointer method. First expand the string to the replaced size, and then traverse from back to front, with i pointing to the end of the new length and j pointing to the end of the old length. At that s[i]!=' 'time , just assign the value of s[i] to s[j] directly. s[i]==' 'When , fill the s[j] position and the two previous positions with %20, and move the j pointer -2 to the filled position %20of %. In the next cycle, both i and j will move forward to the new position. s position. The end condition is that j<iwhen equal to two pointers, it means that there is no need to perform any further operations when the two pointers meet.

Insert image description here

For many array filling problems, you can first expand the array to the filled size, and then operate from back to front.

class Solution {
    
    
public:
    string replaceSpace(string s) {
    
    
        int count = 0; // 统计空格的个数
        int sOldSize = s.size();
        for (int i = 0; i < s.size(); i++) {
    
    
            if (s[i] == ' ') {
    
    
                count++;
            }
        }
        // 扩充字符串s的大小,也就是每个空格替换成"%20"之后的大小
        s.resize(s.size() + count * 2);
        int sNewSize = s.size();
        // 从后先前将空格替换为"%20"
        for (int i = sNewSize - 1, j = sOldSize - 1; j < i; i--, j--) {
    
    
            if (s[j] != ' ') {
    
    
                s[i] = s[j];
            } else {
    
    
                s[i] = '0';
                s[i - 1] = '2';
                s[i - 2] = '%';
                i -= 2;
            }
        }
        return s;
    }
};
  • Time complexity: O( nnn ). where n is the length of string s. Traverse the string s twice, so the time complexity is O(n)
  • Space complexity: O( 1 11 ). We are operating on the original string without using additional space

Guess you like

Origin blog.csdn.net/zss192/article/details/129859989