-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncoder.java
More file actions
44 lines (38 loc) · 1.25 KB
/
Copy pathEncoder.java
File metadata and controls
44 lines (38 loc) · 1.25 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
import java.util.HashMap;
public class Encoder {
private String text;
private HuffmanNode tree;
Encoder(String _text, HuffmanNode _tree) {
this.text = _text;
this.tree = _tree;
}
public HashMap<Character, String> getCodes() {
HashMap<Character, String> map = new HashMap<>();
getCodesHelper(tree, map, new StringBuilder(""));
return map;
}
private void getCodesHelper(HuffmanNode node, HashMap<Character, String> map, StringBuilder str) {
if(node==null)
return;
if(node.getData()!='-') {
map.put(node.getData(), str.toString());
return;
} else {
str.append("0");
getCodesHelper(node.getLeftLeaf(), map, str);
str.deleteCharAt(str.length()-1);
str.append("1");
getCodesHelper(node.getRightLeaf(), map, str);
str.deleteCharAt(str.length()-1);
}
}
public String encodeText() {
StringBuilder str = new StringBuilder("");
HashMap<Character, String> codes = getCodes();
for(int i=0; i<text.length(); i++) {
char c = text.charAt(i);
str.append(codes.get(c));
}
return str.toString();
}
}