Java concise solution with TreeMap


  • 0
    S
    public class Solution {
        public String frequencySort(String s) {
            Map<Character, Integer> map = new HashMap<>();
            TreeMap<Integer, Set<Character>> tm = new TreeMap<>(Collections.reverseOrder());
            char[] array = s.toCharArray();
            for (char c : array) {
                map.put(c, map.getOrDefault(c, 0) + 1);
            }
            for (char c : map.keySet()) {
                int fre = map.get(c);
                if (!tm.containsKey(fre)) {
                    tm.put(fre, new HashSet<>());
                }
                tm.get(fre).add(c);
            }
            StringBuilder sb = new StringBuilder();
            for (Integer fre : tm.keySet()) {
                for (char cur : tm.get(fre)) {
                    for (int i = 0; i < fre; i++) {
                        sb.append(cur);
                    }
                }
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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