LZ78 压缩算法的 Java 实现

LZ78 压缩算法的 Java 实现


1、压缩算法的实现

通过多路搜索树提高检索速度

package com.wretchant.lz78;

import java.util.*;

/**
 多路英文单词查找树
 */
class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
        root.wordEnd = false;
    }

    public void insert(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            Character c = word.charAt(i);
            if (!node.childdren.containsKey(c)) {
                node.childdren.put(c, new TrieNode());
            }
            node = node.childdren.get(c);
        }
        node.wordEnd = true;
    }

    public boolean search(String word) {
        TrieNode node = root;
        for (int i = 0; i < word.length(); i++) {
            Character c = word.charAt(i);
            if (!node.childdren.containsKey(c)) {
                return false;
            }
            node = node.childdren.get(c);
        }
        return node.wordEnd;
    }

}

class TrieNode {
    Map<Character, TrieNode> childdren;
    boolean wordEnd;

    public TrieNode() {
        childdren = new HashMap<Character, TrieNode>();
        wordEnd = false;
    }
}

/**
 编码表
 */
class Output {
    private Integer index;
    private Character character;

    Output(Integer index, Character character) {
        this.index = index;
        this.character = character;
    }

    public Integer getIndex() {
        return index;
    }

    public Character getCharacter() {
        return character;
    }
}

class LZencode {
    @FunctionalInterface
    interface Encode {
        List<Output> encode(String message);
    }

    /**
     构建多路搜索树
     */
    static Trie buildTree(Set<String> keys) {
        Trie trie = new Trie();
        keys.forEach(trie::insert);
        return trie;
    }

    public static final Encode ENCODE = message -> {
        // 构建压缩后的编码表
        List<Output> outputs = new ArrayList<>();
        Map<String, Integer> treeDict = new HashMap<>();
        int mLen = message.length();
        int i = 0;

        while (i < mLen) {
            Set<String> keySet = treeDict.keySet();
            // 生成多路搜索树
            Trie trie = buildTree(keySet);
            char messageI = message.charAt(i);
            String messageIStr = String.valueOf(messageI);
            // 使用多路树进行搜索
            if (!trie.search(messageIStr)) {
                outputs.add(new Output(0, messageI));
                treeDict.put(messageIStr, treeDict.size() + 1);
                i++;
            } else if (i == mLen - 1) {
                outputs.add(new Output(treeDict.get(messageIStr), ' '));
                i++;
            } else {
                for (int j = i + 1; j < mLen; j++) {
                    String substring = message.substring(i, j + 1);
                    String str = message.substring(i, j);
                    // 使用多路树进行搜索
                    if (!trie.search(substring)) {
                        outputs.add(new Output(treeDict.get(str), message.charAt(j)));
                        treeDict.put(substring, treeDict.size() + 1);
                        i = j + 1;
                        break;
                    }
                    if (j == mLen - 1) {
                        outputs.add(new Output(treeDict.get(substring), ' '));
                        i = j + 1;
                    }
                }
            }
        }
        return outputs;
    };


}

2、解压缩算法的实现

package com.wretchant.lz78;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LZdecode {


    @FunctionalInterface
    interface Decode {
        /**
         @param outputs 编码表
         @return 解码后的字符串
         */
        String decode(List<Output> outputs);
    }

    /**
     根据编码表进行解码
     */
    public static final Decode DECODE = (List<Output> outputs) -> {
        StringBuilder unpacked = new StringBuilder();
        Map<Integer, String> treeDict = new HashMap<>();

        for (Output output : outputs) {
            Integer index = output.getIndex();
            Character character = output.getCharacter();
            if (index == 0) {
                unpacked.append(character);
                treeDict.put(treeDict.size() + 1, character.toString());
                continue;
            }
            String term = "" + treeDict.get(index) + character;
            unpacked.append(term);
            treeDict.put(treeDict.size() + 1, term);

        }

        return unpacked.toString();
    };
}

3、测试和使用

package com.wretchant.lz78;

import java.io.InputStream;
import java.util.List;
import java.util.Scanner;
import java.util.function.ToIntFunction;

public class LZpack {

    public static final ToIntFunction<List<Output>> DICT_PRINT = outputs -> {
        outputs.forEach(output -> {
            System.out.println("index :" + output.getIndex() + " char :" + output.getCharacter());
        });
        return 1;
    };

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.println("Please input text ");
        String input = scanner.nextLine();

        LZencode.Encode encode = LZencode.ENCODE;
        List<Output> outputs = encode.encode(input);
        DICT_PRINT.applyAsInt(outputs);
    }
}

测试结果如下
在这里插入图片描述

4、Python 版本的实现代码

def compress(message):
    tree_dict, m_len, i = {}, len(message), 0
    while i < m_len:
        # case I
        if message[i] not in tree_dict.keys():
            yield (0, message[i])
            tree_dict[message[i]] = len(tree_dict) + 1
            i += 1
        # case III
        elif i == m_len - 1:
            yield (tree_dict.get(message[i]), '')
            i += 1
        else:
            for j in range(i + 1, m_len):
                # case II
                if message[i:j + 1] not in tree_dict.keys():
                    yield (tree_dict.get(message[i:j]), message[j])
                    tree_dict[message[i:j + 1]] = len(tree_dict) + 1
                    i = j + 1
                    break
                # case III
                elif j == m_len - 1:
                    yield (tree_dict.get(message[i:j + 1]), '')
                    i = j + 1


def uncompress(packed):
    unpacked, tree_dict = '', {}
    for index, ch in packed:
        if index == 0:
            unpacked += ch
            tree_dict[len(tree_dict) + 1] = ch
        else:
            term = tree_dict.get(index) + ch
            unpacked += term
            tree_dict[len(tree_dict) + 1] = term
    return unpacked


if __name__ == '__main__':
    messages = ['ABBCBCABABCAABCAAB', 'BABAABRRRA', 'AAAAAAAAA']
    for m in messages:
        pack = compress(m)
        unpack = uncompress(pack)
        print(unpack == m)
简简单单OnlineZuozuo CSDN认证博客专家 技术Leader 金融爱好者 诗人
未闻万里蓬莱,而窥先圣遗智。故,以此生筑梦,奔而逐之;以泰山之伟,攀而登之;以静雅素心,处世为人。------zuozuo著
相关推荐
<p> <b><span style="font-size:14px;"></span><span style="font-size:14px;background-color:#FFE500;">【Java面试宝典】</span></b><br /> <span style="font-size:14px;">1、68讲视频课,500道大厂Java常见面试题+100个Java面试技巧与答题公式+10万字核心知识解析+授课老师1对1面试指导+无限次回放</span><br /> <span style="font-size:14px;">2、这门课程基于胡书敏老师8年Java面试经验,调研近百家互联网公司及面试官的问题打造而成,从筛选简历和面试官角度,给出能帮助候选人能面试成功的面试技巧。</span><br /> <span style="font-size:14px;">3、通过学习这门课程,你能系统掌握Java核心、数据库、Java框架、分布式组件、Java简历准备、面试实战技巧等面试必考知识点。</span><br /> <span style="font-size:14px;">4、知识点+项目经验案例,每一个都能做为面试的作品展现。</span><br /> <span style="font-size:14px;">5、本课程已经在线下的培训课程中经过实际检验,老师每次培训结束后,都能帮助同学们运用面试技巧,成功找到更好的工作。</span><br /> <br /> <span style="font-size:14px;background-color:#FFE500;"><b>【超人气讲师】</b></span><br /> <span style="font-size:14px;">胡书敏 | 10年大厂工作经验,8年Java面试官经验,5年线下Java职业培训经验,5年架构师经验</span><br /> <br /> <span style="font-size:14px;background-color:#FFE500;"><b>【报名须知】</b></span><br /> <span style="font-size:14px;">上课模式是什么?</span><br /> <span style="font-size:14px;">课程采取录播模式,课程永久有效,可无限次观看</span><br /> <span style="font-size:14px;">课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化</span><br /> <br /> <br /> <span style="font-size:14px;background-color:#FFE500;"><strong>如何开始学习?</strong></span><br /> <span style="font-size:14px;">PC端:报名成功后可以直接进入课程学习</span><br /> <span style="font-size:14px;">移动端:<span style="font-family:Helvetica;font-size:14px;background-color:#FFFFFF;">CSDN 学院APP(注意不是CSDN APP哦)</span></span> </p>
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页
实付 19.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值