根据出现次数对字符进行排序 Sort Characters By Frequency

本文介绍了一种算法问题的解决方案:根据输入字符串中各字符出现的频率进行降序排序。提供了三种不同的实现方法,包括使用哈希表结合桶排序、堆排序以及直接排序的方法,并附带示例说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题:

Given a string, sort it in decreasing order based on the frequency of characters.

Example 1:

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.

Example 2:

Input:
"cccaaa"
Output:
"cccaaa"
Explanation:
Both 'c' and 'a' appear three times, so "aaaccc" is also a valid answer.
Note that "cacaca" is incorrect, as the same characters must be together.

Example 3:

Input:
"Aabb"
Output:
"bbAa"
Explanation:
"bbaA" is also a valid answer, but "Aabb" is incorrect.
Note that 'A' and 'a' are treated as two different characters.

解决:

① 按照字符出现的次序将字符排序。用hashmap求出现的次数,用桶排序或者堆排序求出排序结果。O(n) 

class Solution { //42ms
    public String frequencySort(String s) {
        Map<Character,Integer> map = new HashMap<>();
        int max = 0;//记录最大出现次数
        for (char c : s.toCharArray()){
            map.put(c,map.getOrDefault(c,0) + 1);
            max = Math.max(max,map.get(c));
        }
        List<Character>[] bucket = new ArrayList[max + 1];
        int count = 0;//记录所有的字符的个数,可以减少时间
        for (char c : map.keySet()){
            int index = map.get(c);
            if (bucket[index] == null){
                bucket[index] = new ArrayList<>();
            }
            bucket[index].add(c);
            count ++;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("");
        for (int i = bucket.length - 1;i >= 0;i --){
            if (bucket[i] != null){
                for (char c : bucket[i]){
                    for (int j = 0;j < i;j ++){
                        sb.append(c);
                    }
                    count --;
                }
                if (count == 0) break;
            }
        }
        return sb.toString();
    }
}

② 堆排序实现。O(nlogn)

class Solution { //52ms
    public String frequencySort(String s) {
        Map<Character,Integer> map = new HashMap<>();
        for (char c : s.toCharArray()){
            map.put(c,map.getOrDefault(c,0) + 1);
        }
        PriorityQueue<Map.Entry<Character,Integer>> priorityQueue = new PriorityQueue<>(new Comparator<Map.Entry<Character, Integer>>() {
            @Override
            public int compare(Map.Entry<Character, Integer> o1, Map.Entry<Character, Integer> o2) {//按照出现次数降序排列
                return o2.getValue() - o1.getValue();
            }
        });
        priorityQueue.addAll(map.entrySet());
        StringBuilder sb = new StringBuilder();
        while(! priorityQueue.isEmpty()){
            Map.Entry e = priorityQueue.poll();
            for (int i = 0;i < (int)e.getValue();i ++){
                sb.append(e.getKey());
            }
        }
        return sb.toString();
    }
}

③ 在discuss中看到的。

class Solution { //8ms
    public String frequencySort(String s) {
        int[] hash = new int[256];//用于统计出现的次数
        char[] res = new char[s.length()];//记录排序后的结果
        for (char c : s.toCharArray()){
            hash[c] ++;
        }
        int i = 0;
        while(i < res.length){
            int max = 0;
            int c = 0;
            for (int j = 0;j < hash.length;j ++){
                if (hash[j] > max){
                    max = hash[j];
                    c = j;
                }
            }
            hash[c] = 0;
            while(max -- > 0){
                res[i ++] = (char) c;
            }
        }
        return new String(res);
    }
}

转载于:https://my.oschina.net/liyurong/blog/1602642

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值