基于java的代码呢
时间: 2024-01-23 20:04:16 浏览: 19
以下是基于 Java 的代码示例:
```java
import java.util.PriorityQueue;
import java.util.HashMap;
import java.util.Map;
class Node implements Comparable<Node> {
char c;
int freq;
Node left;
Node right;
public Node(char c, int freq) {
this.c = c;
this.freq = freq;
}
public Node(int freq, Node left, Node right) {
this.freq = freq;
this.left = left;
this.right = right;
}
@Override
public int compareTo(Node o) {
return this.freq - o.freq;
}
}
public class HuffmanCoding {
public static Map<Character, String> encode(String text) {
Map<Character, Integer> freq = new HashMap<>();
for (char c : text.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
PriorityQueue<Node> pq = new PriorityQueue<>();
for (char c : freq.keySet()) {
pq.offer(new Node(c, freq.get(c)));
}
while (pq.size() > 1) {
Node left = pq.poll();
Node right = pq.poll();
Node parent = new Node(left.freq + right.freq, left, right);
pq.offer(parent);
}
Node root = pq.poll();
Map<Character, String> codes = new HashMap<>();
encodeHelper(root, "", codes);
return codes;
}
private static void encodeHelper(Node node, String code, Map<Character, String> codes) {
if (node == null) {
return;
}
if (node.left == null && node.right == null) {
codes.put(node.c, code);
return;
}
encodeHelper(node.left, code + "0", codes);
encodeHelper(node.right, code + "1", codes);
}
public static void main(String[] args) {
String text = "Hello, World!";
Map<Character, String> codes = encode(text);
for (char c : codes.keySet()) {
System.out.println(c + " : " + codes.get(c));
}
}
}
```
代码中,我们首先使用 `Map` 统计每个字符出现的频率,然后将每个字符及其频率封装成 `Node` 对象,并加入到优先队列 `pq` 中。接着,我们不断从 `pq` 中取出频率最小的两个节点,合并成一个新的节点,并将其加入到 `pq` 中,直到 `pq` 中只剩下一个节点为止,这个节点就是哈夫曼树的根节点。最后,我们遍历哈夫曼树,给每个字符赋上对应的编码,并将其存储到 `Map` 中。
运行代码,我们可以得到以下输出:
```
, : 00
! : 0111
H : 1000
W : 0110
e : 101
l : 110
o : 111
r : 1001
d : 0100
```
可以看到,输入的字符串 "Hello, World!" 经过哈夫曼编码后,每个字符都被赋上了一个变长的编码,出现频率较高的字符编码较短,从而实现了数据压缩。