赫夫曼解码过程实现

package com.coderman.datastruct.tree;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 赫夫曼解码
 * @Author zhangyukang
 * @Date 2020/6/5 12:01
 * @Version 1.0
 **/
public class HuffmanDecodeTest {
    public static void main(String[] args) {
        HTree hTree = new HTree("my name is zhangyukang");
        byte[] data = hTree.getData();
        System.out.println(Arrays.toString(data));
        StringBuilder target = new HuffmanDecoder(data,hTree.huffmanCodeTable).decode();
        System.out.println("==解码后的字符串==");
        System.out.println(target);
    }
}

/**
 * 解码器
 */
class HuffmanDecoder{

    private byte[] source;//源

    //对应的字符编码表
    public  Map<Character,String> huffmanCodeTable;

    public HuffmanDecoder(byte[] source,Map<Character,String> huffmanCodeTable) {
        this.source = source;
        this.huffmanCodeTable=huffmanCodeTable;
    }

    private String byteToBinaryString(boolean flag,byte b){
        int temp=b;
        if(flag){
            temp |=256;
        }
        String str=Integer.toBinaryString(temp);
        if(flag){
            return str.substring(str.length()-8);
        }else{
            return str;
        }
    }

    /**
     * 解码过程
     * @return
     */
    public StringBuilder decode(){
        //1. 先将字节数组转成对应的二进制字符串
        StringBuilder code=new StringBuilder();
        for (int i = 0; i < this.source.length; i++) {
            byte b=this.source[i];
            boolean flag=(i== this.source.length-1);
            code.append(byteToBinaryString(!flag,b));
        }
        System.out.println("==字符数组转二进制==");
        System.out.println(code);
        //2.解码
        //反向获取编码表
        Map<String,Character> map=new HashMap<>();
        for(Map.Entry<Character,String> entry: this.huffmanCodeTable.entrySet()){
            map.put(entry.getValue(),entry.getKey());
        }
        System.out.println("==生成赫夫曼解码表==");
        //查询表
        System.out.println(map);
        //获取解码后的字符
        StringBuilder res=new StringBuilder();   //用于存储返回结果值
        StringBuilder sb=new StringBuilder();    //用于存储当前解码的码值
        for(int i=0;i<code.length();i++){
            sb.append(code.charAt(i));
            Character character = map.get(sb.toString());
            if(character!=null){
                res.append(character.toString());
                sb=new StringBuilder();          //清空
            }
        }
        return res;
    }

}

[-17, 118, 112, 50, 71, -125, 46, -6, -100, 93]
==字符数组转二进制==
1110111101110110011100000011001001000111100000110010111011111010100111001011101
==生成赫夫曼解码表==
{1110=m, 0010=i, 011= , 100=a, 101=n, 0101=u, 0000=e, 1101=g, 0011=k, 0001=h, 0100=s, 1111=y, 1100=z}
==解码后的字符串==
my name is zhangyukang
# 二叉树   算法   数据结构  

评论

公众号:mumuser

企鹅群:932154986

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×