Easy Java solution using comparator


  • 0
    J
    import java.util.Map.Entry;
    public class Solution {
        public String frequencySort(String s) {
            Map<Character, Integer> map = new HashMap<Character, Integer>();
            for (int i = 0; i < s.length(); i++) {
                if (!map.containsKey(s.charAt(i))) {
                    map.put(s.charAt(i), 1);
                } else {
                    map.put(s.charAt(i), map.get(s.charAt(i)) + 1);
                }
            }
    //Descending Sort the entry by the value 
           
            List<Entry<Character, Integer>> listmap = new ArrayList<>(map.entrySet());
          
            Collections.sort(listmap, new Comparator<Entry<Character, Integer>>(){
                public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {
    //if you want to make increasing order just need to 
    // return o1.getValue().compareTo(o2.getValue());
                    return o2.getValue().compareTo(o1.getValue());
                }
            });
            StringBuilder res = new StringBuilder();
            for (Entry<Character, Integer> pair: listmap) {
                int num = pair.getValue();
                char c = pair.getKey();
                for (int i = 0; i < num; i++) {
                    res.append(c);
                }
            }
            return res.toString();
        }
    }
    

Log in to reply
 

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