leetcode solution: Sort Characters By Frequency (451) 发表于 2017-04-20 | 分类于 刷题总结 Given a string, sort it in decreasing order based on the frequency of characters. Example 1:123456789Input:"tree"Output:"eert"Explanation:'e' appears twice while 'r' and 't' both appear once.So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer. Example 2:123456789Input:"cccaaa"Output:"cccaaa"Explanation:Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.Note that "cacaca" is incorrect, as the same characters must be together. Example 3:123456789Input:"Aabb"Output:"bbAa"Explanation:"bbaA" is also a valid answer, but "Aabb" is incorrect.Note that 'A' and 'a' are treated as two different characters. 解法1:Java12345678910111213141516171819202122232425262728public class Solution { public String frequencySort(String s) { Map<Character, Integer> map = new HashMap<Character,Integer>(); for (char c: s.toCharArray()) { map.put(c, map.getOrDefault(c,0) + 1); } List<Map.Entry<Character, Integer>> list = new ArrayList<>(map.entrySet()); Comparator<Map.Entry<Character,Integer>> comparator = new Comparator<Map.Entry<Character, Integer>>() { public int compare(Map.Entry<Character, Integer> left, Map.Entry<Character, Integer> right) { return right.getValue().compareTo(left.getValue()); } }; list.sort(comparator); // Create String StringBuffer ss = new StringBuffer(); for (Map.Entry<Character, Integer> entry : list) { for (int i = 0; i < entry.getValue(); ++i) { ss.append(entry.getKey()); } } return ss.toString(); }}