LC.P451[根据字符出现频率排序]

方法一:哈希表+模拟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public String frequencySort(String s) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
map.merge(c, 1, Integer::sum);
}
List<Character> list = new ArrayList<>(map.keySet());
list.sort((a, b) -> map.get(b) - map.get(a));
StringBuilder builder = new StringBuilder();
for (char c : list) {
builder.append(String.valueOf(c).repeat(map.get(c)));
}
return builder.toString();
}
}
  • 时间复杂度:$O(n + ClogC)$,其中$C=26 + 26 + 10 = 62$,为大写字母、小写字母、数字的数量
  • 空间复杂度:$O(n + C)$