zoukankan      html  css  js  c++  java
  • [剑指offer] 替换空格

    题目描述

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

    刚开始用replace实现了一个replaceAll结果超时。。所以还是直接操作吧:

    先求出新的长度然后从后往前遍历替换。

    我的代码:

    class Solution {
    public:
        void replaceSpace(char *str,int length) {
            int countBlank = 0;
            for (int i = 0; i < length; i++) {
                if (str[i] == ' ') countBlank++;
            }
            int newLength = length + 2 * countBlank;
            int strPos = length;
            for (int i = newLength; i >= 0; i--, strPos--) {
                if (str[strPos] == ' ') {
                    str[i--] = '0';
                    str[i--] = '2';
                    str[i] = '%';
                } else str[i] = str[strPos];
            }
        }
    };
  • 相关阅读:
    飞机大战4-我的子弹
    飞机大战3-我的飞机
    飞机大战1-分析设计
    继承
    常见题
    42个例子算法
    心跳
    tomcat
    service
    URI URL
  • 原文地址:https://www.cnblogs.com/zmj97/p/7895361.html
Copyright © 2011-2022 走看看