Easy Java Solution using PriorityQueue and Map


  • 0
    A
    
           public String frequencySort(String s) {
               if(s.isEmpty()||s.length()<=1)
                   return s;
               HashMap<Character, Integer> charFrequencies = new HashMap<Character, Integer>();
               for(int i=0;i<s.length();i++)
               {
                   if(!charFrequencies.containsKey(s.charAt(i)))
                       charFrequencies.put(s.charAt(i),0);
                   charFrequencies.put(s.charAt(i),charFrequencies.get(s.charAt(i))+1);    
               }
               PriorityQueue<Map.Entry<Character, Integer>> queue = new PriorityQueue<>//((x,y)->x.value-y.value);
               (new Comparator<Map.Entry<Character, Integer>>() {
                   public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2){
                       return o2.getValue()-o1.getValue();}
                   
               }); 
                   
               for(Map.Entry<Character, Integer> entry: charFrequencies.entrySet()){
                   queue.add(entry);
               }    
               StringBuilder sb = new StringBuilder();
               while(queue.size()>0){
                   Map.Entry<Character, Integer> entry = queue.poll();
                   for(int i=0;i<entry.getValue();i++) sb.append(entry.getKey());
               }
               return sb.toString();
               
           }
    

Log in to reply
 

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