leetcode-剑指05-OK

language: C

address

char* replaceSpace(char* s){

    int num_space = 0;
    int getlen(char *st){   //由于还用于算 空格的数量,本函数只能被调用一次
        int count = 0;
        while(st[count] != '\0'){
            if(st[count] ==' ')
                num_space++;
            count++;
        }
        return count;
    }
    int len = getlen(s);
    if(num_space==0)
        return s;

    //确定空格以及位置
    // int i = 0,j=0;
    // int position_space[num_space];
    // while((i<len)&&(j<num_space)){
    //     if(s[i] == ' ')
    //         position_space[j++]=i;
    // }


    s = (char *)realloc(s,sizeof(char) * (len + 2* num_space+1));


// 从后往前移;
    int i,j;
    i = len-1;
    j = i + 2* num_space;
    s[j+1] = '\0';
    while(i != j){
        if(s[i] != ' '){
            s[j--] = s[i--];
        }else{
            s[j--] ='0';
            s[j--] ='2';
            s[j--] ='%';
            i--;
        }
    }
    return s;
}
posted @ 2021-01-26 01:22  RougeBW  阅读(25)  评论(0编辑  收藏  举报