Java Easy Solution PriorityQueue+Map


  • 0
    C
    public class Solution {
        private class Node{
            char c;
            int freq;
            public Node(char c,int freq){
                this.c=c;
                this.freq=freq;
            }
        }
        public String frequencySort(String s) {
            if(s==null || s.length()==0) return s;
            PriorityQueue<Node> p=new PriorityQueue<Node>(new Comparator<Node>(){
                public int compare(Node n1, Node n2){
                    if(n1.freq==n2.freq){
                    return    n1.c-n2.c;
                    }
                    
                    else{
                        
                        return n2.freq-n1.freq;
                    }
                }
            });
            
            HashMap<Character,Integer> map=new HashMap<Character,Integer>();
            
            for(char c:s.toCharArray()){
                map.put(c,map.getOrDefault(c,0)+1);
            }
            
            for(char c:map.keySet()){
                Node temp=new Node(c,map.get(c));
                p.add(temp);
            }
            
            StringBuilder sb=new StringBuilder();
            
            while(p.size()>0){
                Node t=p.poll();
                for(int i=0;i<t.freq;i++)
                    sb.append(t.c);
            }
            
            return sb.toString();
        }
    }
    

Log in to reply
 

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