剑指offer----005(字符串空格替换)

更多题目请点链接:《剑指offer》目录索引


问题描述:

实现一个函数,将字符串中的每个空格替换成%20。例如:”We are
hanppy.“,则输出“We%20are%20happy.”,要求时间复杂度为O(n)

问题分析:

根据描述,此题意思改变字符串内容,并且改变了原字符串长度;
要求时间复杂度为0(n),故不能直接替换;

思路:

第一步,求空格数:要知道改变字符串后的长度,需知道原字符串中空格数,才能确定替换后的字符串长度;
第二步,替换空格:将空格替换成字符串”%20”,替换时,从后往前遍历,遇到空格进行替换,这样做的好处是,可保证原字符串的完整性,不会覆盖原来的字符串(如图)

这里写图片描述

具体代码:

void StringReplace(char* dst, int len)
{
    assert(dst);
    assert(len>0);

     int count = 0,  i = 0;

    while (dst[i] != '\0')
    {
        if (dst[i] == ' ')
        {
            ++count;
        }
        ++i;
    }

    int  index = length ;//原字符串的尾
    int newindex = length + count * 2;//新字符串的长度

    if (newindex  < length)
    {
        return;
    }


    while (index>=0 && newindex>=0)
    {
        if (dst[index] != ' ')
        {
            dst[newindex--] = dst[index];
        }
        else
        {
            dst[newindex--] = '0';
            dst[newindex--] = '2';
            dst[newindex--] = '%';
        }

        index--;
    }


}

测试用例:


void Test()
{

    char arr[30] = "We are happy.";
    int len = strlen(arr);

    printf("%s\n", arr);

    StringReplace(arr, len);

    printf("%s\n",arr);


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值