时间复杂度 O(n)

所有字符只需要移动一次

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return string字符串
     */
    public String replaceSpace (String s) {
        // write code here
        char[] str = s.toCharArray();
        int newLength = str.length;
        for(int i = 0; i < str.length; i++){
            if(str[i] == ' '){
                newLength += 2;
            }
        }
        
        char[] res = new char[newLength];
        int i = str.length - 1;
        int j = newLength - 1;
        for(; i >= 0; i--){
            if(str[i] == ' '){
                res[j--] = '0';
                res[j--] = '2';
                res[j--] = '%';
            }else{
                res[j--] = str[i];
            }
            
        }
        
        
        return new String(res);
    }
}