从数组中删除重复的字符

TCM*_*TCM 6 java arrays algorithm

在阅读一本名为Cracking the coding interview的书时Gayle Laakmann,我遇到了这个问题

设计算法并编写代码以删除字符串中的重复字符,而无需使用任何其他缓冲区.注意:一个或两个额外的变量是好的.数组的额外副本不是.

这段代码: -

 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;
    }
Run Code Online (Sandbox Code Playgroud)

应该从数组中删除重复的字符.我不安静似乎通过一次又一次地替换相同的角色来理解算法正在做什么.我认为只有我觉得算法不起作用,但实际上当我运行这个代码时,它给了我错误的输出.是书中的这个严重错误还是我不理解这个问题?

YoK*_*YoK 7

Algo似乎正在工作,但没有清除剩余的角色.将代码更改为以下并且它可以工作:注意:替换:

str[tail] = 0;
Run Code Online (Sandbox Code Playgroud)

用:

    for(; tail < len;tail++){
        str[tail] = 0;
    }
Run Code Online (Sandbox Code Playgroud)
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;
        }

    }
Run Code Online (Sandbox Code Playgroud)

  • 如果输入是"aa",此代码也会失败 (3认同)