LeetCode refers to Offer 05. Replace spaces

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

The simpler method is to sort out of place, traverse the string once and store it in the result string, so the space complexity is O(n).

If it is required to sort in place, every time a space is traversed, the content after the space is moved back two spaces for storage %20, so the time complexity is O(n²). You can also traverse the string once to calculate the length of the new string, and then copy it from back to front, so that the time complexity is reduced to O(n):

class Solution {
    
    
public:
    string replaceSpace(string s) {
    
    
        int newSz = 0;
        for (char c : s) {
    
    
            if (c == ' ') {
    
    
                newSz += 3;
            } else {
    
    
                ++newSz;
            }
        }

        int oldSz = s.size();
        s.resize(newSz);
        --oldSz;
        --newSz;
        while (newSz != oldSz) {
    
    
            if (s[oldSz] != ' ') {
    
    
                s[newSz--] = s[oldSz--];
            } else {
    
    
                --oldSz;
                s[newSz--] = '0';
                s[newSz--] = '2';
                s[newSz--] = '%';
            }
        }

        return s;
    }
};

Guess you like

Origin blog.csdn.net/tus00000/article/details/112968661