替换空格

163 阅读1分钟

05 替换空格

class Solution {
    //每增加一个空格,长度增加2,首先计算有多少个空格,得到增加后的长度newLength,然后new一个newLength长度的字符数组,从末尾开始遍历替换,减少数组移动的空间
    public String replaceSpace(StringBuffer str) {
        int count = 0;
        int oldLength = str.length();
        for (int i = 0; i < oldLength; i++) {
            if (str.charAt(i) == ' ') {
                count++;
            }
        }
        int newLength = oldLength + 2 * count;
        str.setLength(newLength);
        for (int i = newLength - 1, j = oldLength - 1; j >= 0; i--, j--) {
            if (str.charAt(j) == ' ') {
                str.setCharAt(i, '0');
                str.setCharAt(i - 1, '2');
                str.setCharAt(i - 2, '%');
                i -= 2;
            }else {
                str.setCharAt(i, str.charAt(j));
            }
        }
        return str.toString();
    }
}