Java Solution based on OOD and Priority Queue


  • 0
    I
    1. Map the character and corresponding frequency.
    2. Create Object with values and put them in the priority queue.
    3. Create the String based on each frequency.
    public String frequencySort(String s) {
            StringBuilder sb = new StringBuilder();
            Map<Character, Integer> map = new HashMap<>();
            PriorityQueue<Freq> pq = new PriorityQueue<>((a,b) -> (b.f-a.f));
            for(int i=0;i<s.length();i++){
                char c = s.charAt(i);
                if(!map.containsKey(c)) map.put(c,0);
                map.put(c,map.get(c)+1);
            }
            
            for(Map.Entry<Character,Integer> entry: map.entrySet()){
                Freq fq = new Freq(entry.getKey(),entry.getValue());
                pq.offer(fq);
            }
            
            while(!pq.isEmpty()){
                Freq fr=pq.poll();
                int count=fr.f;
                while(count-->0){
                    sb.append(fr.c);
                }
            }
            return sb.toString();
        }
        
        class Freq{
            char c;
            int f;
            Freq(char c, int f){
                this.c=c;
                this.f=f;
            }
        }
    

Log in to reply
 

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