Huffman

来源:互联网 发布:体育场馆o2o软件 编辑:程序博客网 时间:2024/05/17 07:45

霍夫曼编码的实现

霍夫曼编码

理论概述

引用维基百科中的描述如下:

霍夫曼编码(英语:Huffman Coding),又译为哈夫曼编码赫夫曼编码,是一种用于无损数据压缩的熵编码(权编码)算法。由大卫·霍夫曼在1952年发明。

在计算机数据处理中,霍夫曼编码使用变长编码表对源符号(如文件中的一个字母)进行编码,其中变长编码表是通过一种评估来源符号出现概率的方法得到的,出现概率高的字母使用较短的编码,反之出现概率低的则使用较长的编码,这便使编码之后的字符串的平均长度、期望值降低,从而达到无损压缩数据的目的。

例如,在英文中,e的出现概率最高,而z的出现概率则最低。当利用霍夫曼编码对一篇英文进行压缩时,e极有可能用一个比特来表示,而z则可能花去25个比特(不是26)。用普通的表示方法时,每个英文字母均占用一个字节,即8个比特。二者相比,e使用了一般编码的1/8的长度,z则使用了3倍多。倘若我们能实现对于英文中各个字母出现概率的较准确的估算,就可以大幅度提高无损压缩的比例。

霍夫曼树又称最优二叉树,是一种带权路径长度最短的二叉树。所谓树的带权路径长度,就是树中所有的叶结点的权值乘上其到根结点的路径长度(若根结点为0层,叶结点到根结点的路径长度为叶结点的层数)。树的路径长度是从树根到每一结点的路径长度之和,记为WPL=(W1*L1+W2*L2+W3*L3+…+Wn*Ln),N个权值Wi(i=1,2,…n)构成一棵有N个叶结点的二叉树,相应的叶结点的路径长度为Li(i=1,2,…n)。可以证明霍夫曼树的WPL是最小的。

霍夫曼算法

计算霍夫曼编码首先需要创建一棵霍夫曼树,而创建树的算法基于贪心的思想:

  1. 将所有叶子节点加入优先级队列中(频率从小到大排序)
  2. 每次从队列头部取出两个节点,然后创建 一个新的节点,其孩子为这两个节点,值为二者频率的和。依次进行直到只剩下一个根节点即可。

注意,最优二叉树不是唯一的,为了编码解码唯一,所以,我在实现过程中加了一个判断条件,保证左子树永远小于等于右子树,另外比如对于2,3,5的情况,2和3作为孩子的父节点作为左子树,右子树是5。

有了以上规定,并且编码左子树为0,右子树为1.这样的解是唯一的。

代码实现

package Huffman;import java.util.*;public class code{    static class node implements Comparable<node>    {        int val;        node left;        node right;        int position; //为了保证huffman树的唯一性        node()        {            this.val=-1;            this.left=null;            this.right=null;        }        node(int val)        {            this.val=val;            this.left=null;            this.right=null;        }        @Override        public int compareTo(node o)        {            if (this.val!=o.val)                return this.val-o.val;            else                return this.position-o.position;        }    }    public static void main(String[] args)    {        Scanner in = new Scanner(System.in);        Queue<node> q=new PriorityQueue<>();        int n=in.nextInt();        for (int i=1;i<=n;i++)        {            node tmp=new node();            tmp.val=in.nextInt();            tmp.position=i;            q.add(tmp);        }        while (q.size()>1)        {            node L=q.poll();            node R=q.poll();            node tmp=new node(L.val+R.val);            tmp.left=L;            tmp.right=R;            tmp.position=L.position;            q.add(tmp);        }        res=new HashMap<>();        encode(q.peek(),new ArrayList<>());        for (Integer e:res.keySet())            System.out.println(e+"编码为:"+res.get(e));        List<Integer> tobedecode=new ArrayList<>();        System.out.println("请输入欲解码的编码");        String tmp=in.next();        for (int i=0;i<tmp.length();i++)            tobedecode.add(tmp.charAt(i)-'0');//        System.out.println(tobedecode);        try        {            decode(q.peek(),tobedecode);        }        catch (AssertionError e)        {            System.out.println(e.getMessage());        }    }    private static Map<Integer,List<Integer>> res;    private static void encode(node root,List<Integer> prefix)    {//回溯法打印编码        if (root.right==null&&root.left==null)        {            res.put(root.val,new ArrayList<>(prefix));        }        else        {            prefix.add(0);            encode(root.left,prefix);            prefix.remove(prefix.size()-1);            prefix.add(1);            encode(root.right,prefix);            prefix.remove(prefix.size()-1);        }    }    private static void decode(node root,List<Integer> prefix)    {//解码prefix        if (prefix.size()==0&&root.left==null&&root.right==null)            System.out.println("该编码表示字符的优先级为"+root.val);        else if (prefix.size()>0&&prefix.get(0)==0&&root.left!=null)        {            prefix.remove(0);            decode(root.left,prefix);        }        else if (prefix.size()>0&&prefix.get(0)==1&&root.right!=null)        {            prefix.remove(0);            decode(root.right,prefix);        }        else        {            throw new AssertionError("未能识别的编码");        }    }    private static void print(node root)    {//先序遍历huffman树,debug用        if (root==null)            return;        else        {            System.out.print(root.val+"  ");            print(root.left);            print(root.right);        }    }}

思路很简单,最后加了个先序遍历是为了debug。可以不实现它。

编码过程用了回溯的思想(说白了就是DFS),解码就很简单了,直接从根出发即可。

原创粉丝点击