1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class Solution { public String frequencySort(String s) { StringBuilder result = new StringBuilder(); if (s == null) { return result.toString(); } Map<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()) { if (map.containsKey(c)) { map.put(c, map.get(c) + 1); } else { map.put(c, 1); } } Queue<Character> pq = new PriorityQueue<>((m1, m2) -> map.get(m2) - map.get(m1)); for (char c : map.keySet()) { pq.offer(c); } while (!pq.isEmpty()) { char c = pq.poll(); int size = map.get(c); for (int i = 0; i < size; i++) { result.append(c); } } return result.toString(); } }
|