java - 从数组中删除重复字符

标签 java arrays algorithm

在阅读 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/

相关文章:

java - 不知道为什么intellij语言级别不行

java - hibernate : Splitting table automatically every month

javascript - JS中如何将json转为树形数组?

algorithm - 查找单链表的倒数第 k 个元素 : answer explanation

javascript - 在列表中查找不被列表中其他矩形包含的矩形的最快方法

c++ - 如何优化 vector 的二分查找?

java - 如何在Webots中显示图表?

java - 如何在 Azure 的 Spring Cloud Functions 中 Autowiring 我的 Bean?

c++ - 如何通过组合多个 char 数组来创建 char 数组?

c - 在处理数组时,您会在哪里添加 +1?