-
Notifications
You must be signed in to change notification settings - Fork 0
/
Huffman.java
72 lines (58 loc) · 1.74 KB
/
Huffman.java
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
package MISC;
import java.util.*;
public class Huffman
{
private Node root;
public String encode(String text)
{
char[] ch = text.toCharArray();
PriorityQueue<Node> q = countFrequencies(ch);
root = createTree(q);
Map<Character, String> codemap = createCodeMap();
StringBuilder data = new StringBuilder();
for (char c : ch) data.append(codemap.get(c)+"");
return data.toString();
}
PriorityQueue<Node> countFrequencies(char[] letters)
{
Map<Character, Node> count = new HashMap<>();
for (char ch : letters)
{
if (!count.containsKey(ch)) count.put(ch, new Node(ch));
count.get(ch).add();
}
return new PriorityQueue<>(count.values());
}
Node createTree(PriorityQueue<Node> nodes)
{
while (true)
{
Node node1 = nodes.poll();
Node node2 = nodes.poll();
Node parent = new Node(node1, node2);
if (nodes.isEmpty()) return parent;
nodes.add(parent);
}
}
Map<Character, String> createCodeMap() {
Map<Character, String> result = new TreeMap<>();
root.fillCodeMap(result, "");
return result;
}
public String decode(String data) {
Node current = root;
StringBuilder result = new StringBuilder();
for (char ch : data.toCharArray()) {
if (ch == '0') {
current = current.getLeft();
} else {
current = current.getRight();
}
if (current.isLeaf()) {
result.append(current.getSymbol());
current = root;
}
}
return result.toString();
}
}