计算出现次数并从String中删除重复项

时间:2016-12-16 17:07:57

标签: java duplicates find-occurrences

所以我正在构建一个huffman树,我需要将String作为输入,然后创建包含每个字母的2个数组以及原始字符串中该字母的出现次数,如下所示:

String s = "mississippi"

应该导致:

char[] charArr = {'m','i', 's', 'p'};
int[] count = {1,4,4,2};

关于如何解决这个问题以及很多关于如何解决这个问题的例子有很多问题,特别是在stackoverflow上,但是我设法得到的唯一一个是:

private void findOccurences(String s) {
        List<Character> original = new ArrayList<Character>(s.length());
        List<Character> duplicateRemoved;

        for (int i = 0; i < s.length(); i++) {
            original.add(s.charAt(i));
        }
        duplicateRemoved = new ArrayList<Character>(original);

        // Remove duplicates from second list.
        Set<Character> hs = new HashSet<Character>();
        hs.addAll(duplicateRemoved);
        duplicateRemoved.clear();
        duplicateRemoved.addAll(hs);

        charFreqs = new int[duplicateRemoved.size()];
        charArr = new char[duplicateRemoved.size()];

        for (int i = 0; i < charArr.length; i++) {
            char c = duplicateRemoved.get(i);
            int count = Collections.frequency(original, c);
            charArr[i] = c;
            charFreqs[i] = count;
        }
    }

但它感觉非常笨拙,它也扰乱了数组中字母的顺序。如果我使用它,我得到的数组如下:

char[] charArr = {'p','s', 'i', 'm'};

有没有更好的方法来做我想要的事情?

1 个答案:

答案 0 :(得分:1)

我会这样做

String s = "mississippi";
List<String> original = Arrays.stream(s.split(""))
                     .collect(Collectors.toList());
List<String> duplicateRemoved = Arrays.stream(s.split(""))
                      .distinct()
                      .collect(Collectors.toList());
ArrayList<Integer> Occurrences = new ArrayList<>();
int counter = 1;

for (String aList : duplicateRemoved) {
    counter = (int) original.stream().filter(s1 -> s1.equals(aList)).count();
            Occurrences.add(counter);
        }
System.out.println(duplicateRemoved);
System.out.println(Occurrences);

和输出

enter image description here