在阅读Gayle Laakmann的书《Cracking the coding interview》时,我遇到了这个问题:
设计一个算法并编写代码,在不使用任何额外缓冲区的情况下删除字符串中的重复字符。注意:使用一两个额外变量是可以的,但不能使用数组的额外副本。
以下是代码:
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;
}
这段代码旨在从数组中删除重复字符。我不太理解算法是通过反复替换相同的字符来实现的。我以为只有我觉得算法不起作用,但实际上当我运行这段代码时,它给出了错误的输出。这是书中的严重错误还是我没有理解问题?