Java Solution with TreeMap


  • 0
    Y

    TreeMap by default is sorted by key. Need to override comparator to sort by value descending.

    class Solution {
        
        static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
            SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
                new Comparator<Map.Entry<K,V>>() {
                    @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                        int res = e2.getValue().compareTo(e1.getValue());
                        return res != 0 ? res : 1;
                    }
                }
            );
            sortedEntries.addAll(map.entrySet());
            return sortedEntries;
        }
        
        public String frequencySort(String s) {
            
            StringBuffer sb = new StringBuffer();
            TreeMap<Character, Integer> tmap = new TreeMap<>();
            for (int i=0; i<s.length(); i++) {
                char c = s.charAt(i);
                if (tmap.containsKey(c)) {
                    tmap.put(c, tmap.get(c)+1);
                }
                else {
                    tmap.put(c, 1);
                }
            }
            for (Map.Entry e : entriesSortedByValues(tmap)) {
                int freq = Integer.parseInt(e.getValue().toString());
                for (int i=1; i<=freq; i++) {
                    sb.append(e.getKey().toString());
                }
            }
            return sb.toString();
            
        }
    }
    

Log in to reply
 

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