[剑指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];
        }
    }
};
原文地址:https://www.cnblogs.com/zmj97/p/7895361.html