剑指offer(2)替换空格

剑指offer(2)替换空格

题目

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

剑指offer(2)替换空格

分析

一种高效的方式实现这个函数:先计算出一共有多少个空格,空格数*2就是替换后的字符串比原来的字符串增加的长度,从后向前,遇到一个空格就替换。例如:

We Are Happy中一共有2个空格,赢增加2*2=4个字符的位置。使用一个指针op指向末尾,另一个指针np指向末尾后的第4位,从后向前,将op值拷贝给np,如果op是空格,则使用%20替换,此时op前进一位,而np前进3位。

代码

class Solution {
public:
	void replaceSpace(char *str,int length) {
        char *newstr=str;
        char *oldstr=str;
        int space_count=0;
        while(*oldstr!='\0')
        {
            if(*oldstr==' ')
                space_count++;
            oldstr++;
        }
        newstr=oldstr;
        for(int i=0;i<space_count*2;i++)
        {
            newstr++;
        }
        
        while(oldstr!=newstr)
        {
            if(*oldstr==' ')
            {
                *newstr='0';
                newstr--;
                *newstr='2';
                newstr--;
                *newstr='%';
            }
            else
            {
                *newstr=*oldstr;
            }
            newstr--;
            oldstr--;
        }
	}
};

说明:

上述代码已通过牛客网ac。

参考文章:《剑指offer》

转载请附原文链接。