因此,我正在构建一个霍夫曼树,需要将一个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'};


有什么更好的方法可以做我想要的吗?

最佳答案

我会这样

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);


和输出

java - 计算出现次数并从字符串中删除重复项-LMLPHP

关于java - 计算出现次数并从字符串中删除重复项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41189214/

10-14 04:26