从已排序的Char数组中删除重复项

时间:2015-04-11 04:06:40

标签: java arrays sorting character-arrays

我正在尝试使用下面的字符串,将其转换为数组,对数组进行排序,然后取出任何重复项。我已经到了排序的部分,但当我运行它希望删除重复项时,它似乎打印位置而不是那里的值。

这也是将空格计算为长度,这样我的长度为59。

我可以帮助找出需要改变的内容吗? 谢谢大家!

import java.util.*;

public class Challenge208 {

public static void main(String[] args) {

    String numbers = "3 1 3 4 4 1 4 5 2 1 4 4 4 4 1 4 3 2 5 5 2 2 2 4 2 4 4 4 4 1";
    char[] chars = numbers.toCharArray();
    Arrays.sort(chars);
    System.out.println(chars);

    int current = chars[0];
    boolean found = false;

    for (int i = 0; i < chars.length; i++) {
        if (current == chars[i] && !found) {
            found = true;
        }else if (current != chars[i]) {
            System.out.print(" " + current);
            current = chars[i];
            found = false;
        }
    }
    System.out.print(" " + current);

}
}

3 个答案:

答案 0 :(得分:0)

current应为char而不是int。为了摆脱空间,如果current不是空格,则可以打印。

答案 1 :(得分:0)

而不是使用数组你可以使用treeset ..它将有一个排序顺序,没有重复..但如果在你的场景中你需要数组在这种情况下首先你的当前变量是int而不是char而你没有删除任何duplicates.you只是打印,即使该项目没有任何重复,只有char [0]

答案 2 :(得分:0)

您没有得到数字的索引,但是它的ascii值。有关详细信息:http://www.asciitable.com/ 但解决方案如下:

import java.util.*;

public class Challenge208 {

public static void main(String[] args) {

String numbers = "3 1 3 4 4 1 4 5 2 1 4 4 4 4 1 4 3 2 5 5 2 2 2 4 2 4 4 4 4 1";
char[] chars = numbers.toCharArray();
char[] results = new char[10];
Arrays.sort(chars);
System.out.println(chars);

char current = chars[0];
int size = 0;
boolean found = false;

for (int i = 0; i < chars.length; i++) {
    if (current == chars[i] && !found) {
        found = true;
    }else if (current != chars[i]) {
        System.out.print(" " + current);
        size++;
        current = chars[i];
        found = false;
    }
}

System.out.print(" " + current);
System.out.print("\n"+size);

}
}
相关问题