GuilinDev

Lc0451

05 August 2008

451 Sort Characters By Frequency

一个字符串里的字符按照出现的频率降序排列

按频率排序或桶排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public String frequencySort(String s) {
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        int len = s.length();
        for (int i = 0; i < len; i++) {
            char c = s.charAt(i);
            int frequency = map.getOrDefault(c, 0) + 1;
            map.put(c, frequency);
        }
        List<Character> list = new ArrayList<Character>(map.keySet());
        list.sort((a, b) -> map.get(b) - map.get(a));
        StringBuilder sb = new StringBuilder();
        for (char c : list) {
            int frequency = map.get(c);
            sb.append(String.valueOf(c).repeat(Math.max(0, frequency)));
        }
        return sb.toString();
    }
}