When reading one book with a name Cracking the coding interviewon, Gayle LaakmannI came across this question
Create an algorithm and write code to remove duplicate characters in a string without using any extra buffer. NOTE. One or two additional variables are wonderful. An additional copy of the array is missing.
and this code: -
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;
}
which should remove the duplicate character from the array. I don’t seem to understand what the algorithm does, replacing the same character again and again. I thought that only I feel that the algorithm is not working, but in fact, when I run this code, it gives me the wrong outputs. Is this a serious mistake in the book or didn’t I understand the question?