美文网首页
[剑指offer][02]替换空格

[剑指offer][02]替换空格

作者: FloatingIsland | 来源:发表于2018-06-06 10:14 被阅读0次
    题目描述:

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

    解题思路:
    1. 遍历字符串统计出字符串中空格的总数,并计算替换后字符串的总长度。
    2. 从后往前复制(非空格)替换(遇到空格)。准备p1、p2两个指针。p1指向原始字符串的末尾,而p2指向替换之后的字符串的末尾。接下来向前移动指针p1,逐个把它指向的字符复制到p2指向的位置,直到空格全部处理完成。
    [剑指offer][02]替换空格
    参考代码
    class Solution {
    public:
        void replaceSpace(char *str,int length) {
            //边界检查
            if(!length){
                return;
            }
            //计数
            int count=0;
            int len=0;
            for(int i=0; str[i]!='\0'; i++){
                if(str[i]==' ')
                    count++;
                len++;                
            }
            //没有空格直接返回
            if(!count){
                return;
            }
            //长度越界检查
            int newLen=len+2*count;
            if(newLen+1>length)
                return;
            
            char *p1,*p2;
            p1=str+len-1;
            p2=str+newLen;
            *p2 = '\0';
            p2--;
            while(count){
                if(*p1 !=' '){
                    *p2-- = *p1;          
                }               
                else{
                    *p2-- ='0';
                    *p2-- ='2';
                    *p2-- ='%';
                    count--;
                }
                p1--;
            }
        }
    };
    
    引用链接

    剑指offer面试题:替换空格(将字符串每个空格替换为%20)

    相关文章

      网友评论

          本文标题:[剑指offer][02]替换空格

          本文链接:https://www.haomeiwen.com/subject/voovsftx.html