Java Solution using comparator


  • 0
    D
    public class Solution {
        class myComparator implements Comparator{
            public int compare(Object o1, Object o2) {
                Map.Entry e1 = (Map.Entry) o1;
                Map.Entry e2 = (Map.Entry) o2;
    
                // Reverse
                return (int)e2.getValue() - (int)e1.getValue();
            }
        }
        
        public String frequencySort(String s) {
            Map<String,Integer> map = new HashMap<String,Integer>();
            for (int i = 0; i<s.length(); i++) {
                String key = s.substring(i,i+1);
                if (map.containsKey(key)) {
                    map.put(key,map.get(key)+1);
                }
                else {
                    map.put(key,1);
                }
            }
            List<Map.Entry> list = new ArrayList<>(map.entrySet());
            Collections.sort(list, new myComparator());
            Iterator<Map.Entry> iter = list.iterator();
            StringBuilder sb = new StringBuilder();
            while (iter.hasNext()) {
                Map.Entry entry = iter.next();
                for (int j = 0; j < (int)entry.getValue(); j++) {
                    sb.append(entry.getKey());
                }
            }
            return sb.toString();
        }
    }

Log in to reply
 

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