题目:
Given a string, sort it in decreasing order based on the frequency of characters.
Example 1:
Input: "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:
Input: "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:
Input: "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.
题目描述:
给定一个字符串,根据字符的频率按递减顺序排序。
解题思路:
首先根据字符串中字符和它对应出现的次数,建立哈希表。然后利用桶排序将字符进行排序,即:设置n个桶,根据第i个桶存放出现i次的规则,将全部字符放入桶中,然后从后向前遍历,依次取出排序字符。具体代码及思路如下:
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Sort_BucketSort_FrequencySort_451_1107 { 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>[] buckets = new ArrayList[s.length() + 1]; for (char key : map.keySet()) { int value = map.get(key); if (buckets[value] == null) { buckets[value] = new ArrayList<>(); } buckets[value].add(key); } //从后向前遍历数组 StringBuilder str = new StringBuilder(); for (int i = buckets.length - 1; i >= 0; i--) { if (buckets[i] == null) { continue; } for (char ch : buckets[i]) { for (int j = 1; j <= i; j++) { str.append(ch); } } } return str.toString(); } }