剑指offer-面试题4-替换空格

void test1() {
    char str1[] = "test and test";
    char str2[] = "test and test";
    char * str3 = "test and test";
    char * str4 = "test and test";

    if (str1 == str2) cout << "The pointer 1 and 2 are same!" << endl;
    if (str3 == str4) cout << "The pointer 3 and 4 are same" << endl;
}

把同一个常量字符串赋值给数组,则每个数组都有这个常量字符串的一个拷贝;
把同一个常量字符串赋值给指针,那么这些指针的值相同,都指向同一个位置。
因为在编译的时候编译器会进行优化,所有相同的字符串都会合并成一个并存储在文本段的常量区,所有指向这个字符串的指针都会指向这个字符串的存储区域。

void q4() {
    char str[100] = "We are happy.";
    int len = strlen(str);
    int space_count = 0;
    int i = 0,j = 0;

    for (i = 0; i < len; i++) {
        if (str[i] == ' ') space_count++;
    }
    int len2 = len + 2 * space_count + 1;
    char * tmp = (char *)malloc(sizeof(char)* len2);
    memset(tmp, 0, len2);
    for (i = len-1,j = len2-1-1; i >= 0; i--) {
        if (str[i] == ' ') {
            tmp[j--] = '0';
            tmp[j--] = '2';
            tmp[j--] = '%';
        }
        else {
            tmp[j--] = str[i];
        }
    }
    printf("%s\n", tmp);
    free(tmp);
}

题目二:有两个排序的数组A1和A2,内存在A1的末尾有足够多的空余空间容纳A2。请事先一个函数,把A2中的所有数字插入到A1中并且所有的数字是排序的。
要点:先计算出总共用的空间,然后从后往前遍历,时间复杂度最小,为O(n)。

void q4_1(){
    int str1[100] = {4,7,9,13,15,67,89,234,456,678,999};
    int str2[13] = {6,7,9,13,25,46,68,79,245,457,678,1234,2354};
    int len1 = 11;
    int len2 = 13;
    int len3 = len1 + len2;
    int i = len3 - 1;
    int i1 = len1 - 1;
    int i2 = len2 - 1;

    while (i >= 0) {
        if (str1[i1] >= str2[i2]) {
            str1[i] = str1[i1];
            i--;
            i1--;
        }
        else {
            str1[i] = str2[i2];
            i--;
            i2--;
        }
    }

    for (i = 0; i < len3; i++) {
        printf("%d ",str1[i]);
    }
    printf("\n");
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值