剑指offer第五题 C语言

剑指offer第五题,两个,其实有点不严谨,但思想是这个思想,一个节约空间,另一个好像也没有节约太多的时间(当字符数组长度很大的时候),嗯,就这样

#include<stdio.h>
#include<string.h>

#define SIZE 10
char* replaceSpace(char* s);
char* replaceSpace2(char* s);
int main()
{
    char s[] = "We are happy.";
    puts(s);
    //puts(replaceSpace(s));
    puts(replaceSpace2(s));
    return 0;
}



char* replaceSpace(char* s){
   int count = 0;
   int old_length,new_length;
   int i,j;
   for(i = 0;i < strlen(s);i++)
        if(s[i] == ' ')
            count++;
    old_length = strlen(s);
    new_length = count * 2 + old_length;
    i = new_length;
    j = old_length;
    //printf("%d %d %d\n",count,i,j);
    while(i >= 0 && j >= 0)
    {
        if(s[j] != ' ')
            s[i--] = s[j--];
        else
        {
            j--;
            s[i--] = '0';
            s[i--] = '2';
            s[i--] = '%';
        }
    }
    return s;
}
char* replaceSpace2(char* s){
    char* res = NULL;
    int i = 0,j = 0;
    res = (char*)calloc(strlen(s) * 3 + 1,sizeof(char));
    while(s[j] != '\0')
    {
        if(s[j] != ' ')
            res[i++] = s[j++];
        else
        {
            j++;
            res[i++] = '%';
            res[i++] = '2';
            res[i++] = '0';
        }
    }
    return res;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值