Java Hashmap and PriorityQueue Solution getting TLE


  • 0
    S

    can someone explain why

    public class Solution {
        public String frequencySort(String s) {
            HashMap<Character,Integer> map= new HashMap<>();
            
            for(int i=0;i<s.length();i++){
                map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0)+1);
            }
            
            Comparator<Map.Entry<Character,Integer>> valcomp = 
            Map.Entry.<Character,Integer>comparingByValue().reversed();
            
            PriorityQueue<Map.Entry<Character,Integer>> pq=new PriorityQueue<>(valcomp);
            
            pq.addAll(map.entrySet());
            
            String res="";
            
            while(true){
                Map.Entry<Character,Integer> entry= pq.poll();
                if(entry==null)
                    break;
                for(int i=0;i<entry.getValue();i++){
                    res+=Character.toString(entry.getKey());
                }
            }
            
            return res;
        }
    
    }

Log in to reply
 

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