哈夫曼编码

2020-04-30 16:14:21

问题描述:

请设计一个算法,给一个字符串进行二进制编码,使得编码后字符串的长度最短。

输入

MT-TECH-TEAM

输出

33

问题求解:

本质就是按照频率建哈夫曼树,需要注意的是最后的深度其实就是合并的次数,没合并一次则深度加一。

    private int encode(String s) {
        char[] chs = s.toCharArray();
        Map<Character, Integer> map = new HashMap<>();
        for (char c : chs) map.put(c, map.getOrDefault(c, 0) + 1);
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (char c : map.keySet()) pq.add(map.get(c));
        int res = 0;
        while (pq.size() > 1) {
            int q1 = pq.poll();
            int q2 = pq.poll();
            int curr = q1 + q2;
            pq.add(curr);
            res += curr;
        }
        return res;
    }

  

原文地址:https://www.cnblogs.com/hyserendipity/p/12809515.html