剑指offer————替换空格c++实现

问题:请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

思路:从前往后移动,移动的次数太多,从后往前移动,移动的次数刚好!

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 ;
	}
};

猜你喜欢

转载自blog.csdn.net/qq_17141957/article/details/80099695