这是来自《Cracking the Coding Interview》书中的内容。
设计一个算法并编写代码,以在不使用任何额外缓冲区的情况下删除字符串中的重复字符。注意:使用一个或两个额外变量是可以的,但不能使用数组的额外副本。
根据书中所说,时间复杂度为$O(N^2)$。我们如何从解决方案中确定时间复杂度为$O(N^2)$?我对解决方案如何去除重复字符有疑问,我已经在下面的内联注释中包含了它们。
设计一个算法并编写代码,以在不使用任何额外缓冲区的情况下删除字符串中的重复字符。注意:使用一个或两个额外变量是可以的,但不能使用数组的额外副本。
根据书中所说,时间复杂度为$O(N^2)$。我们如何从解决方案中确定时间复杂度为$O(N^2)$?我对解决方案如何去除重复字符有疑问,我已经在下面的内联注释中包含了它们。
public static void removeDuplicates(char[] str) {
if (str == null) return; // if the array is empty return nothing?
int len = str.length; // get the length of the array
if (len < 2) return; // if the array length is only 1 return nothing?
int tail = 1; // initialise tail variable as 1 !
// Why are we starting at second character here (at i = 1),why not start at i = 0 ?
for (int i = 1; i < len; ++i) {
int j;
for (j = 0; j < tail; ++j) { // so are we checking if j is less then 1 as tail has been initialized to 1
if (str[i] == str[j]) break; // stop, if we find duplicate.
}
if (j == tail) { why are we comparing j to tail(1) here ?
str[tail] = str[i]; // assigning the value
++tail; // incrementing tail
}
}
str[tail] = 0; //setting last element as 0
}
-
char[] arr = {'a','b','a','b'};removeDuplicates(arr);System.out.println(Arrays.toString(arr));
,输出是[a, b, , b]
。 - Paul Boddington