哈夫曼编码java代码
时间: 2024-03-31 17:30:54 浏览: 125
哈夫曼编码是一种用于数据压缩的算法,它通过将出现频率较高的字符用较短的编码表示,从而实现对数据的压缩。下面是一个简单的哈夫曼编码的Java代码示例:
```java
import java.util.*;
class HuffmanNode implements Comparable<HuffmanNode> {
char data;
int frequency;
HuffmanNode left, right;
public HuffmanNode(char data, int frequency) {
this.data = data;
this.frequency = frequency;
left = right = null;
}
public int compareTo(HuffmanNode node) {
return this.frequency - node.frequency;
}
}
public class HuffmanCoding {
public static void main(String[] args) {
String text = "Hello, World!";
Map<Character, Integer> frequencyMap = buildFrequencyMap(text);
HuffmanNode root = buildHuffmanTree(frequencyMap);
Map<Character, String> huffmanCodes = buildHuffmanCodes(root);
System.out.println("Huffman Codes:");
for (Map.Entry<Character, String> entry : huffmanCodes.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
private static Map<Character, Integer> buildFrequencyMap(String text) {
Map<Character, Integer> frequencyMap = new HashMap<>();
for (char c : text.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
return frequencyMap;
}
private static HuffmanNode buildHuffmanTree(Map<Character, Integer> frequencyMap) {
PriorityQueue<HuffmanNode> pq = new PriorityQueue<>();
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
pq.add(new HuffmanNode(entry.getKey(), entry.getValue()));
}
while (pq.size() > 1) {
HuffmanNode left = pq.poll();
HuffmanNode right = pq.poll();
HuffmanNode parent = new HuffmanNode('\0', left.frequency + right.frequency);
parent.left = left;
parent.right = right;
pq.add(parent);
}
return pq.poll();
}
private static Map<Character, String> buildHuffmanCodes(HuffmanNode root) {
Map<Character, String> huffmanCodes = new HashMap<>();
buildHuffmanCodesRecursive(root, "", huffmanCodes);
return huffmanCodes;
}
private static void buildHuffmanCodesRecursive(HuffmanNode node, String code, Map<Character, String> huffmanCodes) {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
huffmanCodes.put(node.data, code);
}
buildHuffmanCodesRecursive(node.left, code + "0", huffmanCodes);
buildHuffmanCodesRecursive(node.right, code + "1", huffmanCodes);
}
}
```
这段代码实现了哈夫曼编码的基本功能,包括构建字符频率映射、构建哈夫曼树和生成哈夫曼编码。你可以根据需要进行修改和扩展。
阅读全文