Short solution by Java 8 Stream API

  • 0
    public String frequencySort(String s) {
        final List<Map.Entry<Integer, Long>> list = s.chars().boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet()
                .stream().sorted(Map.Entry.<Integer, Long> comparingByValue().reversed()).collect(Collectors.toList());
        final char[] res = new char[s.length()];
        int idx = 0;
        for (Map.Entry<Integer, Long> entry : list) {
            Arrays.fill(res, idx, idx += entry.getValue().intValue(), (char) entry.getKey().intValue());
        return new String(res);
        // ideally, it can be written with open source library AbacusUtil
        // return CharStream.from(s).boxed().groupBy(Function.identity(), Collectors.counting()).sorted(Map.Entry.<Character, Long> comparingByValue().reversed())
        //        .flatMapToChar(e -> CharStream.repeat(e.getKey(), e.getValue())).join("");

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.