java short solution use stream


  • 0
    C
     public String frequencySort(String s) {
            Map<Character, Integer> map = new HashMap<>();
            for(char ch : s.toCharArray()) {
                if(!map.containsKey(ch)) map.put(ch, 0);
                map.put(ch,map.get(ch)+1);
            }
           List<Character> ranked = map.entrySet().stream()
                                .sorted((e1,e2) -> e2.getValue().compareTo(e1.getValue()))
                                .map(e -> e.getKey())
                                .collect(Collectors.toList());
           StringBuilder sb = new StringBuilder();
            for(char ch : ranked) {
                int count = map.get(ch);
                while(count-- > 0) {
                    sb.append(ch);
                }
            }
            return sb.toString();
        }
    

Log in to reply
 

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