The sword refers to the offer————replace the space c++ implementation

Question: Please implement a function to replace spaces in a string with "%20". For example, when the string is We Are Happy., the replaced string is We%20Are%20Happy.

Ideas: move from front to back, the number of moves is too many, move from back to front, the number of moves is just right!

class Solution {
public:
	void replaceSpace(char *str,int length) {
         if(str==NULL||length<0)
             return ;
        int spacecnt=0;
        int i=0;
        int oldLength=0;
        while(str[i]!='\0')
        {
            oldLength++;
             if(str[i]==' ')
                spacecnt++;
            i++;
        }
        int newLength=oldLength+2*spacecnt;
        if(newLength>length)
            return ;
        int p1=oldLength;
        int p2=newLength;
        while(p1>=0&&p2>p1)
        {
            if(str[p1]==' ')
            {
                str [p2 -] = '0';
                str [p2 -] = '2';
                str [p2 -] = '%';
            }
            else
            {
                str [p2 -] = str [p1];
            }
            p1--;
        }
        return ;
	}
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325483776&siteId=291194637