剣指Offer置換スペースの問題


1、テーマの説明
1つの文字列の各スペースを「%20」に置き換える関数を実装してください.例えば、文字列がWe Are Happyである.置換後の文字列は、We%20 Are%20 Happyである.
2、コード一:
import java.util.*;
public class Solution {
    public String replaceSpace(StringBuffer str) {
        StringBuilder sb = new StringBuilder();
        for(int i=0;i

このコードはどうしてACができないのか分からない.
コード2:
public class Solution {
    public String replaceSpace(StringBuffer str) {
        return str.toString().replace(" ", "%20");	
    }
}

もう一つの考え方:
  • 解法一:Javaが持参した関数str.toString()を用いる.replace("","%20").
  • 解法2:現在の文字列に置換します.
  • 置換後の文字列がどれだけの空間を必要とするかを先に計算し、元の文字列空間を拡張する.
  • 文字列を後ろから前に置き換えると、文字列ごとに1回だけ移動する必要があります.
  • 前後の場合、各文字列は複数回移動する必要があり、効率が低い.

  • 解法3:新しい文字列を開きます.

  • コード3:
    public class Solution {
        public String replaceSpace(StringBuffer str) {
            int spacenum = 0;
            for(int i = 0; i < str.length(); i++){
                if(str.charAt(i) == ' '){
                    spacenum++;
                }
            }
            int oldLength = str.length();
            int oldIndex = oldLength - 1;
            int newLength = oldLength + spacenum*2;
            str.setLength(newLength);
            int newIndex = newLength - 1;
            for(; oldIndex >= 0 && oldLength < newLength; oldIndex--){
                if(str.charAt(oldIndex) == ' '){
                    str.setCharAt(newIndex--, '0');
                    str.setCharAt(newIndex--, '2');
                    str.setCharAt(newIndex--, '%');
                }else{
                    str.setCharAt(newIndex--, str.charAt(oldIndex)); 
                #         ,               。
                }
            }
            return str.toString();
        }
    }

    双针の方法は恐ろしくて、ここの针はどうして自分で走ることができますか?
    参照リンク:https://blog.csdn.net/qq_35025383/article/details/87936054