import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
/**
* 451.根据字符出现频率排序
*
* 桶排序 + 优先队列
*/
public class Solution451 {
// 内置类,用于关联每一个字符串和它出现的次数
static class CharNum{
CharNum(char ch, int chNum){
this.ch = ch;
this.chNum = chNum;
}
public char ch;
public int chNum;
}
public String frequencySort(String s) {
// Hash 简单的桶排序
Map<Character, Integer> charIntegerMap = new HashMap<>();
char[] chars = s.toCharArray();
for (char ch : chars) {
charIntegerMap.put(ch, charIntegerMap.getOrDefault(ch, 0) + 1);
}
// 优先队列
Queue<CharNum> queue = new PriorityQueue<>((o1, o2) -> {
// 自定义比较器
if (o1.chNum != o2.chNum)
return o2.chNum - o1.chNum;
else
return o2.ch - o1.ch;
});
for (Map.Entry<Character, Integer> entry : charIntegerMap.entrySet()) {
CharNum charNum = new CharNum(entry.getKey(), entry.getValue());
queue.add(charNum);
}
// 生成答案
StringBuilder stringBuilder = new StringBuilder();
while(!queue.isEmpty()) {
CharNum charNum = queue.poll();
for (int i = 0; i < charNum.chNum; i++) {
stringBuilder.append(charNum.ch);
}
}
return stringBuilder.toString();
}
}
LeetCode -- 451.根据字符出现频率排序
最新推荐文章于 2024-04-02 20:43:27 发布