//System.out.println(isPermutation("aXbcx", "xbcaX"));
をコメントアウトすることで
私は、私はちょうど十分であるかもしれないよりよい解決策に
あなたのソリューションを提案したいあなたは
@sudoは、あなたの質問に答えCTCIを解決している見ることができますが、StringBuilder.appendがcharを倍増することを説明する価値があります容量が十分でない場合、それは文字列を保持できるようになるまで、それぞれの文字列が含まれています配列サイズは、追加
返されるchar配列
private static char[] URLify(char[] original) {
char charToReplace = ' ';
char[] replacement = new char[]{'%', '2', '0'};
// count charToReplace, in our case, count spaces
int numCharsToReplace = 0;
for (char c : original) if (c == charToReplace) numCharsToReplace++;
// creating new fixed char array to return
int resultSize = original.length + (numCharsToReplace * replacement.length) - numCharsToReplace;
char[] result = new char[resultSize];
// we need two indexes,one to iterate the result char array, second to iterate the original
int i = 0, originalIdx = 0;
// until we set all new array of chars cells
while (i < resultSize) {
// get original character
char curOriginalChar = original[originalIdx];
// this condition is first because I assume real URL will not contain as much spaces as chars
// if current character is not one we need to replace, copy
if (curOriginalChar != charToReplace) {
result[i] = curOriginalChar;
// for readable code the index incremented in new line
// could be replaced with "result[i++] = curOriginalChar;"
i++;
}
else {
for (char c : replacement) {
result[i] = c;
i++;
}
}
originalIdx++;
}
return result;
}
に拡大しませんが、元の文字列の上に二回繰り返されます私のソリューション
ユーティリティ使用例に
/**
* StringBuilder's member "char value[]" is the character array stored inside StringBuilder, and it's
* reference can be accessed only through getValue method, which is not public
* so a little hack so we can know what is the char array size created
*/
private static int getStringBuilderCharSize(StringBuilder sb) throws NoSuchFieldException, IllegalAccessException {
Field stringBuilderCharField = StringBuilder.class.getSuperclass().getDeclaredField("value");
stringBuilderCharField.setAccessible(true);
char[] chars = (char[]) stringBuilderCharField.get(sb);
return chars.length;
}
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
String original = "Mr & Mrs Smith";
char[] urlify = URLify(original.toCharArray());
System.out.println(new String(urlify) + "|" + urlify.length);
StringBuilder sb = new StringBuilder();
for (char c : original.toCharArray())
if (c != ' ') sb.append(c);
else sb.append("%20");
System.out.println(sb.toString() + "|" + getStringBuilderCharSize(sb));
}
出力のStringBuilder実際のchar配列の長さを得るために:保存
Mr%20&%20Mrs%20Smith|20
Mr%20&%20Mrs%20Smith|34
14細胞;)
単に 's.replace(」」、 "%20")'をしないのはなぜ '他に' 何それは –
だろうか? – QBrute
なぜ[URLEncoder#encode](https://docs.oracle.com)を使用しないでください。com/javase/7/docs/api/java/net/URLEncoder.html) – sudo