Java Solution using PriorityQueue


  • 0
    G
    public class Solution {
        public String frequencySort(String str) {
            
            StringBuilder result=new StringBuilder();
            int[] letters=new int[256];
            PriorityQueue<Container> heap=new PriorityQueue<Container>((o1,o2)->(o2.frequency-o1.frequency));
            
            for(int i=0;i<str.length();i++) {    
                letters[str.charAt(i)]++;
            }
            
            for(int i=0;i<letters.length;i++) {
                int b=i;
                char c=(char)b;
                if(letters[i]>0)heap.add(new Container(c,letters[i]));
            }
            
            while(!heap.isEmpty()) {
                Container c=heap.remove();
                for(int j=0;j<c.frequency;j++) {
                    result.append(c.character);
                }
            }
            return result.toString();
        }
    }
    
    class Container{
        char character;
        int frequency;
        public Container(char character,int frequency) {
            this.character=character;
            this.frequency=frequency;
        }
    }
    

Log in to reply
 

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