Posted onInLeetcode
,
Bucket sort Symbols count in article: 919Reading time ≈1 mins.
Question
Given a string s, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.
Return the sorted string. If there are multiple answers, return any of them.
classSolution{ public String frequencySort(String s){ Map<Character, Integer> map = new HashMap<>(); for (char c : s.toCharArray()) map.put(c, map.getOrDefault(c, 0) + 1); List<Character> [] bucket = new List[s.length() + 1]; for (char key : map.keySet()){ int frequency = map.get(key); if (bucket[frequency] == null) bucket[frequency] = new ArrayList<>(); bucket[frequency].add(key); } StringBuilder sb = new StringBuilder(); for (int pos = bucket.length - 1; pos > 0; pos--) if (bucket[pos] != null) for (char c : bucket[pos]) for (int i = 0; i < pos; i++) sb.append(c); return sb.toString(); } }