我开始阅读著名的“破解编程面试”一书。
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.
我在这里找到了一个类似的主题:Remove the duplicate characters in a string
作者给出的解决方案是:
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;
}
这里的问题是作者使用数组作为这个函数的参数。所以我的问题是:如何编写以 STRING 作为参数的算法?因为我觉得在这里使用数组真的更容易,就像你“避免了练习的困难”(在我看来,我是一个新的 Java 开发人员)。
如何编写这样的算法?
最佳答案
Java 字符串是不可变的,因此您不能在不将数组复制到缓冲区的情况下对字符串执行此操作。
关于java - 在Java中删除字符串中的重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36830001/