-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHuffmanCoding.java
More file actions
84 lines (63 loc) · 2.12 KB
/
HuffmanCoding.java
File metadata and controls
84 lines (63 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.*;
class HuffmanNode {
char character;
int frequency;
HuffmanNode left;
HuffmanNode right;
HuffmanNode(char character, int frequency) {
this.character = character;
this.frequency = frequency;
}
}
class HuffmanComparator implements Comparator<HuffmanNode> {
public int compare(HuffmanNode x, HuffmanNode y) {
return x.frequency - y.frequency;
}
}
public class HuffmanCoding {
static Map<Character, String> huffmanCodes;
private static void generateCodes(HuffmanNode root, String code) {
if (root == null)
return;
if (root.left == null && root.right == null) {
huffmanCodes.put(root.character, code);
}
generateCodes(root.left, code + "0");
generateCodes(root.right, code + "1");
}
private static HuffmanNode buildTree(String text) {
int[] freq = new int[256];
for (char c : text.toCharArray()) {
freq[c]++;
}
PriorityQueue<HuffmanNode> pq = new PriorityQueue<>(new HuffmanComparator());
for (int i = 0; i < 256; i++) {
if (freq[i] > 0) {
pq.add(new HuffmanNode((char) i, freq[i]));
}
}
while (pq.size() > 1) {
HuffmanNode left = pq.poll();
HuffmanNode right = pq.poll();
HuffmanNode parent = new HuffmanNode('-', left.frequency + right.frequency);
parent.left = left;
parent.right = right;
pq.add(parent);
}
return pq.poll();
}
private static String encode(String text) {
StringBuilder encoded = new StringBuilder();
for (char c : text.toCharArray()) {
encoded.append(huffmanCodes.get(c));
}
return encoded.toString();
}
// ✅ Web-friendly method
public static String encodeText(String text) {
huffmanCodes = new HashMap<>();
HuffmanNode root = buildTree(text);
generateCodes(root, "");
return encode(text);
}
}