my java solution use the Map and the Collections.sort,it is easy understand


  • 1
    L
    public String frequencySort(String s) {
          TreeMap<Character,Integer> map = new TreeMap<>();
          for(int i = 0; i < s.length(); i++){
              char c = s.charAt(i);
              Integer count = map.get(c) == null ? 0 : map.get(c);
              map.put(c,count+1);
          }
        List<Map.Entry<Character,Integer>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list,new myCmp());
        StringBuffer buffer = new StringBuffer();
        for(Map.Entry<Character,Integer> entry : list){
            for(int i = 0; i < entry.getValue(); i++){
                buffer.append(entry.getKey());
            }
        }
        return buffer.toString();
    
    }
    static class myCmp implements Comparator<Map.Entry<Character,Integer>>{
        @Override
        public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {
           return  o2.getValue() - o1.getValue();
        }
    }

Log in to reply
 

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