troubleasy

导航

 

请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

思路:计算空格个数;从后向前移动字符和插入字符;时间复杂度O(n)

void replaceSpace(char *str,int length) {
        int count=0;
        for(int i=0;i<length;i++)
        {
            if(str[i]==' ')
            {
                count++;
            }
        }
        for(int j=length-1;j>=0;j--)
        {
            if(str[j]!=' ')
                str[j+count*2]=str[j];
            else{
                count--;
                str[j+count*2]='%';
                str[j+count*2+1]='2';
                str[j+count*2+2]='0';
            }
        }
    }

posted on 2020-05-25 16:59  troubleasy  阅读(88)  评论(0编辑  收藏  举报