註釋掉
//System.out.println(isPermutation("aXbcx", "xbcaX"));
我可以看到你正在解決中鼎
@sudo回答你的問題,我只是想提出一個更好的解決方案
您的解決方案可能是不夠好,但它是值得說明的是StringBuilder.append將增加一倍炭追加數組大小,將包含字符串每個如果容量不夠,直到它可以容納字符串
我的解決方案將迭代兩次在原來的字符串,但不會擴大返回的字符數組
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的實際字符數組長度
/**
* 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));
}
輸出:
Mr%20&%20Mrs%20Smith|20
Mr%20&%20Mrs%20Smith|34
14細胞保存;)
什麼別的「難道是 –
爲什麼不能簡單地做's.replace(」」, 」%20「)'? – QBrute
爲什麼不使用[URLEncoder#encode](https://docs.oracle。COM/JavaSE的/ 7 /文檔/ API/JAVA /淨/ URLEncoder.html)? – sudo