【Leetcode】451. 根据出现的频率对字符排序(Sort Characters By Frequency)
程序员文章站
2022-05-13 21:26:06
...
Leetcode - 451 Sort Characters By Frequency (Medium)
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.
解题思路:桶排序,使用元素的出现频次作为下标。
public String frequencySort(String s) {
List<Character>[] bucket = new List[s.length() + 1];
Map<Character, Integer> frequencyMap = new HashMap<>();
for (char c : s.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
for (char key : frequencyMap.keySet()) {
int frequency = frequencyMap.get(key);
if (bucket[frequency] == null) {
bucket[frequency] = new ArrayList<>();
}
bucket[frequency].add(key);
}
StringBuffer sb = new StringBuffer();
for (int i = bucket.length - 1; i > 0; i--) {
if (bucket[i] == null) continue;
for (char c : bucket[i]) {
for (int j = i; j > 0; j--) {
sb.append(c);
}
}
}
return sb.toString();
}
上一篇: C++:数组的引用,作形参或是作返回类型,不用指针
下一篇: 商城项目运维篇,简单理解~
推荐阅读
-
【Leetcode】451. 根据出现的频率对字符排序(Sort Characters By Frequency)
-
LeetCode 451. 根据字符出现频率排序(Sort Characters By Frequency)
-
LeetCode | 0451. Sort Characters By Frequency根据字符出现频率排序【Python】
-
LeetCode 451. Sort Characters By Frequency 按照字符频率排序(Java实现)
-
LeetCode 22 May, Sort Characters By Frequency, 按字符出现频率排序字符串
-
Leetcode 451.根据字符出现频率排序(Sort Characters By Frequency)
-
451 Sort Characters By Frequency 根据字符出现频率排序
-
Sort Characters By Frequency 根据字符出现频率排序
-
LeetCode——451. 根据字符出现频率排序(Sort Characters By Frequency)[中等]——分析及代码(Java)
-
[LeetCode] 451. Sort Characters By Frequency 根据字符出现频率排序