Java HashMap Solution


  • 0
    M
    public class Solution {
        public String frequencySort(String s) {
            Map<Character, Integer> map = new HashMap<>();
            for (char c : s.toCharArray()) {
                if (!map.containsKey(c)) {
                    map.put(c, 0);
                }
                map.put(c, map.get(c) + 1);
            }
            List<Map.Entry<Character, Integer>> list = new LinkedList<>();
            for (Map.Entry<Character, Integer> m : map.entrySet()) {
                list.add(m);
            }
            Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>(){
                public int compare(Map.Entry<Character, Integer> m1, Map.Entry<Character, Integer> m2) {
                    return m2.getValue() - m1.getValue();
                }
            });
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<Character, Integer> m : list) {
                for (int i = 0; i < m.getValue(); i++) {
                    sb.append(m.getKey());
                }
            }
            return sb.toString();
        }
    }~~~

Log in to reply
 

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