在閱讀名爲Cracking the coding interview
由Gayle Laakmann
一本書,我遇到了這個問題刪除重複的字符數組從
設計算法和編寫代碼來刪除字符串中的字符重複不 使用任何額外的緩衝。注意:一個或兩個 附加變量都可以。數組的額外副本不是。
和驗證碼 -
public static void removeDuplicates(char[] str) {
if (str == null) {
return;
}
int len = str.length;
if (len < 2) {
return;
}
int tail = 1;
for (int i = 1; i < len; ++i) {
int j;
for (j = 0; j < tail; ++j) {
if (str[i] == str[j]) {
break;
}
}
if (j == tail) {
str[tail] = str[i];
++tail;
}
}
str[tail] = 0;
}
這是應該從數組中刪除重複的字符。我不安靜,似乎通過一次又一次地替換相同的字符來理解算法在做什麼。我認爲只有我覺得算法不起作用,但實際上當我運行這段代碼時,它給了我錯誤的輸出。這是書中的嚴重錯誤還是我沒有理解這個問題?
如果輸入是「aa」 – 2014-06-21 12:21:17
for char [] str = {'a','a'},則此代碼也會失敗。它給出[a,] – EMM 2015-10-20 16:34:37