首页 > 其他 > 详细

剑指offer JZ-2

时间:2021-01-03 10:52:03      阅读:28      评论:0      收藏:0      [点我收藏+]

题目描述

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

 

 
 

思路1:

每多一个空格,则新的字符串会多出两个空间,所以申请一个新的字符串如下: char *array = new char[length + 2*space]

遍历原字符串,按照修改规则向新字符串中逐个添加字符。而后将新字符的内容拷贝给原字符串

技术分享图片
class Solution {
public:
    void replaceSpace(char *str,int length) {
        int space = 0;
        for(int i=0;i<length;i++)
        {
            if(*(str+i) ==  )
            {
                space++;
            }
        }
        char *array = new char[length + 2*space];
        int new_pos = 0;
        for(int i=0;i<length;i++)
        {
            if(*(str+i)!=  )
            {
                *(array+new_pos++) = *(str+i);
            }
            else
            {
                *(array+new_pos++) = %;
                *(array+new_pos++) = 2;
                *(array+new_pos++) = 0;
            }
        }
        delete[] str;
        str = new char[new_pos];
        strcpy(str,array);
    }
};
View Code

思路2:

在不开辟新的字符串的情况下,直接在原字符串上做更改。

为了保证“无后效性”,逆序扫描原字符串,并将当前扫描的字符,填充在新位置。

技术分享图片
class Solution {
public:
    void replaceSpace(char *str,int length) {
        if(str == nullptr || length<=0)
            return;
        int space = 0;
        for(int i=0;i<length;i++)
        {
            if (*(str+i)== )
                space++;
        }
        if(!space) return;
        int old_pos = length;
        int new_pos = length+2*space;
        for(int i=old_pos;i>=0;i--)
        {
            if(*(str+i) !=  )
            {
                *(str+new_pos--) = *(str+i);
            }
            else
            {
                *(str+new_pos--) = 0;
                *(str+new_pos--) = 2;
                *(str+new_pos--) = %;
            }
        }
    }
};
View Code

 

注意事项:

应注意细节上的实现,比如:

  在执行后续操作前,通过 if(str == nullptr || length<=0) 检查传入的是否为空指针
  若原字符串中没有空格,则不需要进行后续操作

 

剑指offer JZ-2

原文:https://www.cnblogs.com/alan-W/p/14224514.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!