字符串替换

来源:互联网 发布:ios9 数据流量 开关 编辑:程序博客网 时间:2024/06/08 18:23

题目:
请实现一个函数,把字符串的每个空格替换成“%20”。
例如:
输入”We are Happy.”则输出”We%20are%20happy.”

算法描述1:
1)利用循环,计算字符串长度(‘\0’也算),空格个数
2)更改后字符串的长度为:原长度+2*空格个数
将一根指针放到更改后字符串末尾的位置,另一根指针放到没有更改的字符串的末尾,
进行复制.
时间复杂度:(O(n))

#include<stdio.h>#include<stdlib.h>#include<string.h>void Str_Change_Space(char str[]){    int  length, count,length2;    for (count = 0, length = 0; str[length]; length++)    {        if (str[length] == ' ')        {            count++;            }    }    length++;//加上'\0'    length2 = length+ 2 * count;    while (length2-length)    {        if (str[length] - ' ')        {            str[length2--] = str[length];        }        else        {            str[length2--] = '0';            str[length2--] = '2';            str[length2--] = '%';        }           length--;    }}int main(void){    char str[30] = "We are Happy.";    Str_Change_Space(str);    puts(str);    system("pause");    return 0;}

算法描述2:
从前到后依次遍历,遇到空格,后面的元素向后面移动2个单位
之后再将%20插入到空格处
时间复杂度(O(n^2))

#include<stdio.h>#include<stdlib.h>#include<string.h>void Insert_Symbol(char str[]){    int i, j;    for (i = 0; str[i];)    {        if (str[i]==' ')//如果遇到空格,后面元素向后移动2个单位        {            for (j = strlen(str); j-i; j--)            {                str[j + 2] = str[j];            }            //在空格位置插入%20            str[i++] = '%';            str[i++] = '2';            str[i++] = '0';        }        else        {            i++;        }    }}int main(void){    char str[30] = " hello world ";    Insert_Symbol(str);    puts(str);    system("pause");    return 0;}

举一反三:
有两个有序数组,A1和A2,内存在A1的末尾有足够的空间容纳A2
请实现一个函数,把A2中的所有数字插入A1中,并且所有数字是有序的。
算法描述:
1)先统计A1,A2的长度L1,L2,哪么合并后长度为A1,A2长度之和即L1+L2,
2)将两根指针分别放到L1,L2处,比较a[L1-1]和a[L2-1]的大小,
将较大的放大到A1[L1+L2-1]的位置,
较大的元素所在数组长度减1
直到L1或者L2中有一个数组长度为零
结束循环,将剩下的数组复制到A1中。

#include<stdio.h>#include<stdlib.h>void Combine(int a[], int n, int b[], int m){    int length1, length2;    if (!a || n <= 0 || !b || m <= 0)    {        return;    }    length1 = n;    length2 = m;    while (length1  && length2 )    {        if (a[length1 - 1] > b[length2 - 1])        {            a[length1 + length2 - 1] = a[length1 - 1];            printf("a,a[%d]=%5d\n", length1 + length2 - 1, a[length1 + length2 - 1]);            length1--;        }        else        {            a[length1 + length2 - 1] = b[length2-1 ];                printf("b,a[%d]=%5d\n", length1 + length2 - 1,a[length1 + length2 - 1]);            length2--;        }    }    if (length2)//如果b数组没有处理完,将剩余部分全部复制到a数组中    {        for (; length1 < length2; length1++)        {            a[length1] = b[length1];        }    }}int main(void){    int a[100] = { 1,2,3,4,5,6,7 };    int b[10] = { 2,3,4,5,6,7 };    Combine(a, 7, b, 6);    for (int i = 0; a[i]; i++)    {        printf("%5d",a[i]);    }    system("pause");    return 0;}
原创粉丝点击