剑指 Offer 05. 替换空格

剑指 Offer 05. 替换空格

请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

示例 1:

输入:s = “We are happy.”
输出:“We%20are%20happy.”

方法一:

遍历添加

由于每次替换从 1 个字符变成 3 个字符,使用字符数组可方便地进行替换。建立字符数组地长度为 s 的长度的 3 倍,这样可保证字符数组可以容纳所有替换后的字符。

class Solution {
    public String replaceSpace(String s) {
        int length = s.length();
        char[] array = new char[length * 3];
        int size = 0;
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == ' ') {
                array[size++] = '%';
                array[size++] = '2';
                array[size++] = '0';
            } else {
                array[size++] = c;
            }
        }
        String newStr = new String(array, 0, size);
        return newStr;
    }
}

采用StringBuilder进行数组的追加字符

class Solution {
    public String replaceSpace(String s) {
        StringBuilder res = new StringBuilder();
        for(Character c : s.toCharArray())
        {
            if(c == ' ') res.append("%20");
            else res.append(c);
        }
        return res.toString();
    }
}

方法二:原地修改

在这里插入图片描述

public class Solution {

    public String replaceSpace(String s) {
        int spaceCount = 0;
        char[] chars = s.toCharArray();
        for (char c : chars) {
            if (c == ' ') {
                spaceCount++;
            }
        }
        char[] newChars = Arrays.copyOf(chars, chars.length + spaceCount * 2);
        for (int oldIndex = chars.length - 1, newIndex = newChars.length - 1; oldIndex < newIndex; oldIndex--, newIndex--) {
            if (newChars[oldIndex] != ' ') {
                newChars[newIndex] = newChars[oldIndex];
            } else {
                newChars[newIndex--] = '0';
                newChars[newIndex--] = '2';
                newChars[newIndex] = '%';
            }
        }
        return new String(newChars);
    }

    public static void main(String[] args) {
        String string = "we are Chinese";
        String string1 = "            ";
        String string2 = "";
        String string3 = " ";
        String string4 = " we are Chinese ";
        Solution replaceBlankInString = new Solution();
        System.out.println(replaceBlankInString.replaceSpace(string));
        System.out.println(replaceBlankInString.replaceSpace(string1));
        System.out.println(replaceBlankInString.replaceSpace(string2));
        System.out.println(replaceBlankInString.replaceSpace(string3));
        System.out.println(replaceBlankInString.replaceSpace(string4));
    }
}

posted @ 2021-01-24 22:19  your_棒棒糖  阅读(24)  评论(0)    收藏  举报