又通过一道题目,替换字符串 —— 剑指Offer

https://www.nowcoder.net/practice/4060ac7e3e404ad1a894ef3e17650423?tpId=13&tqId=11155&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

class Solution {
public:
    void replaceSpace(char *str,int length) {
        if (str == NULL) return;
        int bcnt = 0;
        for (int i = 0; i<length; ++i) {
            if (str[i] == ' ') bcnt++;
        }
        
        int nlen = length + 2 * bcnt;
        for (int i=length-1, j=nlen-1; i >= 0 && j >= 0; i--, j--) {
            if (str[i] != ' ') str[j] = str[i];
            else {
                str[j] = '0';
                str[--j] = '2';
                str[--j] = '%';
            }
        }
    }
};

解题关键:

字符串的长度会变化。要注意。
另外,就是从后往前来拷贝字符。
原文地址:https://www.cnblogs.com/charlesblc/p/8424758.html