Realize replace spaces

[Title] Please implement a function, a string in each space replaced by "20%." For example, when the string is We Are Happy. After the string is replaced after We% 20Are% 20Happy.

[Thinking] beginning was thinking, but replacement back from the front, nor no, but will find that if there are two spaces, then "Happy" will be moved twice, which would decrease the efficiency can not be moved once We will do it? To break the inertia of thinking, from moving forward just fine! After determining the length of the direct "Happy" to the last, just once!

class Solution {
public:
    void replaceSpace(char *str,int length) {
        int count = 0;
        for(int i =0;i < length; i++){
            if(str[i] == ' ')
                count++;
        }
        for(int i = length; i >= 0; i--){
            if(str[i] != ' ')
            {
                str[i + 2*count] = str[i];
            }
            else{
                str[i+2*count] = '0';
                str[i+2*count-1] = '2';
                str[i+2*count-2] = '%';
                count--;
            }
        }
    }
};

 

Guess you like

Origin www.cnblogs.com/zhudingtop/p/11291257.html