Java solution using map and a max heap


  • 0
    L
    public String frequencySort(String s) {
            if(s.length()==0) {
                return "";
            }
            
            Map<Character,Integer> map = new HashMap<>();
            for(char c : s.toCharArray()) {
                map.put(c,map.getOrDefault(c,0)+1);
            }
            PriorityQueue<Pair> heap = new PriorityQueue<Pair>(Collections.reverseOrder());
            for(Map.Entry<Character,Integer> e : map.entrySet()) {
                if(e.getValue()>0) {
                    heap.add(new Pair(e.getKey(),e.getValue()));
                }
            }
            StringBuilder builder = new StringBuilder();
            while(!heap.isEmpty()) {
                Pair p = heap.poll();
                p.toString(builder);
            }
            return builder.reverse().toString();
            
            
            
            
        }
        private class Pair implements Comparable<Pair>{
            int count;
            char c;
            Pair(char c, int count) {
                this.c = c;
                this.count=count;
            }
            public int compareTo(Pair p) {
                return Integer.compare(p.count,count);
            }
            
            public void toString(StringBuilder builder ) {
                for(int i=0;i<count;i++) {
                    builder.append(c);
                }
            }
        }
    

Log in to reply
 

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