Java Solution with heap


  • 1
    A

    public class Solution {
    public String frequencySort(String s) {

        Map<Character,StringBuilder> map = new HashMap<>();
        String res = "";
        
        if(s==null||s.length()<=0) return res;
        for(int i=0;i<s.length();i++){
            char ch = s.charAt(i);
            if(!map.containsKey(ch))
                map.put(ch,new StringBuilder());
            map.get(ch).append(ch);
        }
        
        PriorityQueue<Map.Entry<Character,StringBuilder>> queue = new PriorityQueue<>(map.size(), new Comparator<Map.Entry<Character, StringBuilder>>(){
            public int compare(Map.Entry<Character, StringBuilder> en1, Map.Entry<Character, StringBuilder> en2){
                return -(en1.getValue().length() - en2.getValue().length());
            }
        });
        
        
        
        for(Map.Entry<Character,StringBuilder> en:map.entrySet()){
            queue.add(en);
        }
        
        while(queue.size()!=0)
            res+=queue.poll().getValue().toString();
        return res;
    }
    

    }


Log in to reply
 

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