Java 實(shí)現(xiàn)LZ78壓縮算法的示例代碼
LZ78 壓縮算法的 Java 實(shí)現(xiàn)
1、壓縮算法的實(shí)現(xiàn)
通過多路搜索樹提高檢索速度
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);
}
/**
構(gòu)建多路搜索樹
*/
static Trie buildTree(Set<String> keys) {
Trie trie = new Trie();
keys.forEach(trie::insert);
return trie;
}
public static final Encode ENCODE = message -> {
// 構(gòu)建壓縮后的編碼表
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);
// 使用多路樹進(jìn)行搜索
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);
// 使用多路樹進(jìn)行搜索
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、解壓縮算法的實(shí)現(xiàn)
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);
}
/**
根據(jù)編碼表進(jìn)行解碼
*/
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);
}
}
測試結(jié)果如下

4、Python 版本的實(shí)現(xiàn)代碼
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)
到此這篇關(guān)于Java 實(shí)現(xiàn)LZ78壓縮算法的文章就介紹到這了,更多相關(guān)Java LZ78壓縮算法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在RedisTemplate中使用scan代替keys指令操作
這篇文章主要介紹了在RedisTemplate中使用scan代替keys指令操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
Java 中Timer和TimerTask 定時器和定時任務(wù)使用的例子
這篇文章主要介紹了Java 中Timer和TimerTask 定時器和定時任務(wù)使用的例子,非常具有實(shí)用價值,需要的朋友可以參考下2017-05-05
Java使用注解實(shí)現(xiàn)防止重復(fù)提交實(shí)例
這篇文章主要介紹了Java使用注解實(shí)現(xiàn)防止重復(fù)提交實(shí)例,在一些項目中由于用戶誤操作,多次點(diǎn)擊表單提交按鈕,會產(chǎn)生很多次的數(shù)據(jù)交互,為了解決這一問題,本文使用注解來實(shí)現(xiàn)防止重復(fù)提交,需要的朋友可以參考下2023-07-07
Spring框架中Bean的三種配置和實(shí)例化方法總結(jié)
在Spring框架中,Bean的配置和實(shí)例化是很重要的基礎(chǔ)內(nèi)容,掌握各種配置方式,才能靈活管理Bean對象,本文將全面介紹Bean的別名配置、作用范圍配置,以及構(gòu)造器實(shí)例化、工廠實(shí)例化等方式2023-10-10
Java緩存Map設(shè)置過期時間實(shí)現(xiàn)解析
這篇文章主要介紹了Java緩存Map設(shè)置過期時間實(shí)現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-12-12
JAVA JSP頁面技術(shù)之EL表達(dá)式整理歸納總結(jié)
這篇文章主要介紹了java中JSP頁面技術(shù)之EL表達(dá)式概念作用以及語法等的使用,需要的朋友可以參考2017-04-04
通過Docker啟動Solace并在Spring?Boot通過JMS整合Solace的操作方法
本文將介紹如何在Spring中使用,雖然代碼使用的是Spring Boot,但并沒有使用相關(guān)starter,跟Spring的整合一樣,可通用,JMS是通過的消息處理框架,可以深入學(xué)習(xí)一下,不同的MQ在JMS的整合上都是類似的,感興趣的朋友跟隨小編一起看看吧2023-01-01
SpringBoot @FixMethodOrder 如何調(diào)整單元測試順序
這篇文章主要介紹了SpringBoot @FixMethodOrder 調(diào)整單元測試順序方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09

