public class Solution {
    public String replaceSpace(StringBuffer str) {
        int len = str.length();
        int rightMoveCount = 0;
        for(int i = 0; i < len; i++) {
            int newIndex = i + rightMoveCount;
            if(' ' == str.charAt(newIndex)) {
                str.replace(newIndex, newIndex+1 , "%20");
                rightMoveCount += 2;
            }
        }
        return str.toString();
    }
}

3个字符替换1个字符,导致的结果就是原来数组元素的索引要+2。第一次替换+2,第二次替换+2*2,以此类推,只有这样才能够在新数组中遍历初始数组中的空格并完成替换。