gpt4 book ai didi

java - 在Java中删除字符串中的重复字符

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:38:54 25 4
gpt4 key购买 nike

我开始阅读著名的“破解编程面试”一书。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com