[Java Solution] use TreeMap to sort.


  • 0
    public class Solution {
    public String frequencySort(String s) {
        Map<Character,Integer> map=new HashMap<Character,Integer>();
        //collect the <char,count> to a HashMap
        char[] array=s.toCharArray();
        for(char c:array){
            map.put(c,map.getOrDefault(c,0)+1);
        }
        //sort <count,charList> with TreeMap
        TreeMap<Integer,List<Character>> tp=new TreeMap<Integer,List<Character>>();
        for(char c:map.keySet()){
            int count=map.get(c);
            if(!tp.containsKey(count)) tp.put(count,new ArrayList<Character>());
            tp.get(count).add(c);
        }
        //go through the TreeMap from last
         StringBuilder res=new  StringBuilder();
         while (tp.size()>0){
            Map.Entry<Integer, List<Character>> entry = tp.pollLastEntry();
            List<Character> chars=entry.getValue();
            int count=entry.getKey();
            for(int i=0;i<chars.size();i++){
                 for(int j=0;j<count;j++){
                   res.append(chars.get(i));
            }
            }
        }
        return res.toString();
    }
    

    }


Log in to reply
 

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