zoukankan      html  css  js  c++  java
  • 剑指offer JZ-2

    题目描述

    请实现一个函数,将一个字符串中的每个空格替换成“%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';
                }
            }
            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) 检查传入的是否为空指针
      若原字符串中没有空格,则不需要进行后续操作

  • 相关阅读:
    怎样判断某个分辨率是不是 16:9
    最简单的判断是否为IE浏览器的方法
    S4 smartforms切换到非word编辑器
    字符串中数字和汉字之前打空格
    elasticsearch 中term查询
    小程序 反编译 pc微信
    vue-element-admin vue-amap使用高德地图 文档没有示例代码
    高德地图 自适应 显示多个点标记
    laravel5 清理 bootstrap/cache/config.php
    element-admin 上传 跨域 问题 http-request
  • 原文地址:https://www.cnblogs.com/alan-W/p/14224514.html
Copyright © 2011-2022 走看看