[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){
        //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>());
        //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++){
        return res.toString();


Log in to reply

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