在阅读名为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