下面是一个简单的Java实现哈夫曼编码的例子。这个例子中,我们假设输入是一个字符串,并且我们使用哈夫曼树对每个字符的出现频率进行编码。
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
public class HuffmanCoding {
static class Node implements Comparable<Node> {
char character;
int frequency;
Node left, right;
Node(char character, int frequency) {
this.character = character;
this.frequency = frequency;
}
@Override
public int compareTo(Node other) {
return this.frequency - other.frequency;
}
}
public static void huffmanCoding(String input) {
// 统计每个字符的出现频率
HashMap<Character, Integer> frequencyMap = new HashMap<>();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
// 创建哈夫曼树的节点
Queue<Node> nodes = new PriorityQueue<>();
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
nodes.add(new Node(entry.getKey(), entry.getValue()));
}
// 构建哈夫曼树
while (nodes.size() > 1) {
Node left = nodes.poll();
Node right = nodes.poll();
Node parent = new Node('\0', left.frequency + right.frequency);
parent.left = left;
parent.right = right;
nodes.add(parent);
}
// 从哈夫曼树构建编码
HashMap<Character, String> huffmanCodes = new HashMap<>();
buildCodes(nodes.poll(), "", huffmanCodes);
// 输出每个字符的哈夫曼编码
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
System.out.println(entry.getKey() + ": " + huffmanCodes.get(entry.getKey()));
}
}
private static void buildCodes(Node node, String code, HashMap<Character, String> huffmanCodes) {
if (node == null) return;
if (node.character != '\0') {
huffmanCodes.put(node.character, code);
} else {
buildCodes(node.left, code + "0", huffmanCodes);
buildCodes(node.right, code + "1", huffmanCodes);
}
}
public static void main(String[] args) {
String input = "this is an example for huffman coding";
huffmanCoding(input);
}
}