为了练习,我想在java中按频率排序ASCII字符串,然后按字母顺序排序,所以'banana'应该变成'bnnaaa','grammar'应该变成'gaammrr'。这是我到目前为止所拥有的。
public static orderByFrequencyAndThenAlphabet(String str) {
// 128 ASCII characters possible.
int[] charCount = new int[128]
// Get the counts.
str = str.toCharArray();
for (char c : str) {
charCount[int(c)] += 1;
}
// Sort by frequency...
}
如您所见,我创建了一个数据结构来存储输入字符串中每个字符的计数。但是,我现在如何使用数据结构按频率对字符进行排序?我应该考虑使用优先队列吗?