剑指offer - 02替换空格

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

有三种思路:

1. 从前向后,遇到空格,则把后面左右字符向后移动两个位置,移动次数较多

2. 从前向后遍历一次,计算空格个数count,新申请strlen + 2*count 大小的内存,从前向后遍历赋值,最后copy回原str

3. 从前向后遍历一次,计算空格个数count,从strlen + 2*count的位置开始向前,依次赋值(最后一个字符为‘\0’)

代码如下:

class Solution {
public:
    //方法1:从前向后 遇到空格则把后面的字符都向后移动2个位置
    //方法2:申请一块新的内存 从前向后遇到空格则替换
    void replace_spaces_by_memory(char *str,int length){
        //可以先从前向后遍历一次计算空格的个数 下面这里偷懒了
        char* newstr = (char*)malloc(length*3 + 1);
        int   index  = 0;
        for(int i = 0; i < length; i++)
        {
            if(str[i] == ' ')
            {
                newstr[index++] = '%';
                newstr[index++] = '2';
                newstr[index++] = '0';
            }
            else
            {
                newstr[index++] = str[i];
            }
        }
        newstr[index] = '\0';
        memcpy(str, newstr, index);
        free(newstr);
    }
    
    //方法3:从前向后计算空格数量 从后向前移动替换
    void replace_space_by_move(char* str, int length){
        int count = 0;
        for(int i = 0; i < length; i++){
            if(str[i] == ' '){
                count++;
            }
        }
        int strIndex = length;
        int newIndex = length + 2*count;  //每出现一个空格 则比原有字符串多出两个字符
        while(strIndex >= 0)
        {
            if(str[strIndex] == ' '){
                str[newIndex--] = '0';
                str[newIndex--] = '2';
                str[newIndex--] = '%';
                strIndex--;
            }
            else{
                str[newIndex--] = str[strIndex--];
            }
        }
    }
    
	void replaceSpace(char *str,int length) {
        replace_spaces_by_memory(str, length);
        //replace_space_by_move(str, length);
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值