Solution Using HashMap and TreeMap


  • 0
    S

    class Solution {
    public String frequencySort(String s) {
    Map<Character,Integer> map= new HashMap<Character,Integer>();
    char[] chrs = s.toCharArray();

        for(char c : chrs){
           if(map.containsKey(c)){
               map.put(c,map.get(c)+1);
           }
            else{
                map.put(c,1);
            }
        }
        Map<Integer,List<Character>> sortFreq= new HashMap<Integer,List<Character>>(); 
        for(Map.Entry<Character,Integer> m : map.entrySet()){
            if(sortFreq.containsKey(m.getValue())){
                ArrayList<Character> test = new ArrayList<Character>(sortFreq.get(m.getValue()));
                test.add(m.getKey());
                sortFreq.put(m.getValue(),test);
            }
            else{
                sortFreq.put(m.getValue(),Arrays.asList(m.getKey()));
            }
        }
        Map<Integer,List<Character>> treeMap = new TreeMap<Integer,List<Character>>(Collections.reverseOrder());
        treeMap.putAll(sortFreq);
        StringBuffer sb = new StringBuffer();
        for(Map.Entry<Integer,List<Character>> entry : treeMap.entrySet()){
            for(char c: entry.getValue()){
                int num = entry.getKey();
                while(num!=0){
                    sb.append(c);
                    num = num-1;
                }
            }
        }
        return sb.toString();
    }
    

    }


Log in to reply
 

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