哈夫曼树、编码构造,实现文件压缩(Java)

哈夫曼树、编码介绍

哈夫曼树

给定N个权值作为N个叶子结点,构造一棵二叉树,若该树的带权路径长度达到最小,称这样的二叉树为最优二叉树,也称为哈夫曼树(Huffman Tree)。哈夫曼树是带权路径长度最短的树,权值较大的结点离根较近。

哈夫曼编码

哈夫曼编码(Huffman Coding),又称霍夫曼编码,是一种编码方式,哈夫曼编码是可变字长编码(VLC)的一种。 Huffman于1952年提出一种编码方法,该方法完全依据字符出现概率来构造异字头的平均长度最短的码字,有时称之为最佳编码,一般就叫做Huffman编码(有时也称为霍夫曼编码)。

代码(含注释)

package;

import lombok.Data;
import sun.misc.IOUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

// 编码,解码测试
class TestCode {
   
    public static void main(String[] args) {
   

//        String str = "abcde";
//        String str = "ab";
        String str = "Huffman code test";
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        HuffmanCode huffmanCode = new HuffmanCode(bytes);

        System.out.println("- - - - - - - - - - - ");
        System.out.println("编码映射:");
        for (Map.Entry<Byte, String> entry : huffmanCode.getCodeMap().entrySet()) {
   
            System.out.println((char) entry.getKey().byteValue() + "->" + entry.getValue());
        }
        System.out.println("- - - - - - - - - - - ");

        byte[] zipBytes = HuffmanCode.coding(huffmanCode.getCodeMap(), bytes);
        byte[] decodingBytes = HuffmanCode.decoding(huffmanCode.getCodeMap(), zipBytes);
        System.out.println("压缩后 = " + Arrays.toString(zipBytes));
        System.out.println("解压后 = " + Arrays.toString(decodingBytes));

        System.out.println("原字符串: " + str);
        System.out.println("还原结果: " + new String(decodingBytes));
    }
}

// 文件压缩,解压测试
class TestZip {
   
    public static void main(String[] args) {
   
        String orgPath, destPath;
        Scanner scan = new Scanner(System.in);
        System.out.println("待压缩文件路径:");
        orgPath = scan.next();

        //压缩
        int endIndexOfPoint = orgPath.lastIndexOf('.');
        destPath = orgPath.substring(0, endIndexOfPoint) + ".zip";
        HuffmanCode.zip(orgPath, destPath);
        System.out.println("已将 " + orgPath + " 压缩到:" + destPath);

        //解压
        orgPath = orgPath.substring(0, endIndexOfPoint) + "(1)" + orgPath.substring(endIndexOfPoint);
        HuffmanCode.unZip(destPath, orgPath);
        System.out.println("已将 " + destPath + " 解压到:" + orgPath);
        scan.close();
    }
}

/**
 * Desc: 哈夫曼树
 * 当用 n 个结点(都做叶子结点且都有各自的权值)试图构建一棵树时,
 * 如果构建的这棵树的带权路径长度最小,称这棵树为“最优二叉树”,
 * 有时也叫“赫夫曼树”或者“哈夫曼树”。
 *
 * @author pikachu
 * @date: 2022/8/15 14:44
 */


@Data
public class HuffmanCode {
   
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值