Simple Java Solution using PriorityQueue


  • 0
    D
        public String frequencySort(String s) {
            Map<Character,Integer> map = new HashMap<>();
            char[] ca = s.toCharArray();
            for (int i = 0; i < ca.length; i++) {
                map.put(ca[i], map.getOrDefault(ca[i], 0) + 1);
            }
            
            PriorityQueue<Character> pq = new PriorityQueue<>((x, y) -> map.get(y) - map.get(x));
            
            for (char c : map.keySet()) {
                pq.offer(c);
            }
            StringBuilder sb = new StringBuilder();
            while (!pq.isEmpty()) {
                char c = pq.poll();
                int count = map.get(c);
                for (int i = 0; i < count; i++) sb.append(c);
            }
            return sb.toString();
        }

Log in to reply
 

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