【字符串替换】程序员面试金典——1.4空格替换

Solution1:我的答案

20181007重做

class Replacement {
public:
    string replaceSpace(string iniString, int length) {
        // write code here
        int space_nums = 0;
        for (int i = 0; i < length; i++) {
            if (iniString[i] == ' ')
                space_nums++;
        }
        iniString += string(2*space_nums, ' ');
        int i = length + 2*space_nums - 1, j = length - 1;
        while (i != j) {
            if (iniString[j] == ' ') {
                iniString[i--] = '0';
                iniString[i--] = '2';
                iniString[i--] = '%';
                j--;
            } else {
                iniString[i--] = iniString[j--];
            }
        }
        return iniString;
    }
};

在原字符串上改

class Replacement {
public:
    string replaceSpace(string iniString, int length) {
        // write code here
        if(length == 0) return iniString;
        int num_of_blank = 0;
        for(int i = 0; i < length; i++) {
            if(iniString[i] == ' ')
                num_of_blank++;
        }
        string temp(num_of_blank * 2, ' ');
        iniString.append(temp);
        int i = length - 1, j = length + num_of_blank * 2 - 1;
        while(i != j) {
            if(iniString[i] != ' ') {
                iniString[j--] = iniString[i];
            }
            else if(iniString[i] == ' ') {
                iniString[j--] = '0';
                iniString[j--] = '2';
                iniString[j--] = '%';
            }
            i--;
        }
        return iniString;
    }
};

Solution2:

参考网址:https://www.nowcoder.com/profile/7890003/codeBookDetail?submissionId=12718468
生成新的字符串,写法很简单啊~

class Replacement {
public:
    string replaceSpace(string iniString, int length) {
        // write code here
        string str="";
        for(int i=0;i

你可能感兴趣的:(程序员面试金典题目笔记)