Solution using HashMap and TreeMap


  • 1
    L

    ..
    public String frequencySort(String s) {

        if(s.length()==0 || s==null) return "";
        
        HashMap<Character, Integer> map = new HashMap<>();
        TreeMap<Integer, Queue<Character>> tmap = new TreeMap<Integer, Queue<Character>>(Collections.reverseOrder());
        StringBuilder sb = new StringBuilder();
        
        for(int i=0;i<s.length();i++){
            if(map.containsKey(s.charAt(i)))
                map.put(s.charAt(i), map.get(s.charAt(i))+1);
            else
                map.put(s.charAt(i),1);
        }
        
        for(int val: map.values()){
            tmap.put(val,new LinkedList<>());
        }
        
        for(Map.Entry<Character,Integer> m: map.entrySet()){
                char key = m.getKey();
                int val = m.getValue();
                Queue<Character> q = tmap.get(val);
                q.add(key);
                tmap.put(val,q);
        }
        
        
        for(Map.Entry<Integer, Queue<Character>> tm: tmap.entrySet()){
            int count = tm.getKey();
            Queue<Character> qu = tm.getValue();
            
            while(!qu.isEmpty()){
                int tcount = count;
                char c = qu.poll();
                    while(tcount!=0){
                        sb.append(c);
                        tcount--;
                    }
            }
        }
        
        return sb.toString();
        
        
        
    }

Log in to reply
 

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