在阅读 Gayle Laakmann
的一本名为 Cracking the coding interview
的书时,我遇到了这个问题
Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not.
和这段代码:-
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;
}
应该从数组中删除重复的字符。我不安静似乎通过一次又一次地替换相同的字符来理解算法在做什么。我认为只有我觉得该算法不起作用,但实际上当我运行这段代码时它给了我错误的输出。这是书中的严重错误还是我没有理解问题?
最佳答案
Algo 似乎可以正常工作,但无法清除剩余字符。 将代码更改为以下并且它有效: 注意:已替换:
str[tail] = 0;
与:
for(; tail < len;tail++){
str[tail] = 0;
}
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;
}
}
for(; tail < len;tail++){
str[tail] = 0;
}
}
关于java - 从数组中删除重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3398153/