forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLZW.java
More file actions
46 lines (37 loc) · 1.12 KB
/
LZW.java
File metadata and controls
46 lines (37 loc) · 1.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
package com.thealgorithms.compression;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implementation of LZW (Lempel–Ziv–Welch) compression algorithm.
* Reference: https://en.wikipedia.org/wiki/Lempel–Ziv–Welch
*/
public final class LZW {
private LZW() {
throw new UnsupportedOperationException("Utility class");
}
public static List<Integer> compress(String input) {
int dictSize = 256;
Map<String, Integer> dictionary = new HashMap<>();
for (int i = 0; i < 256; i++) {
dictionary.put("" + (char) i, i);
}
String w = "";
List<Integer> result = new ArrayList<>();
for (char c : input.toCharArray()) {
String wc = w + c;
if (dictionary.containsKey(wc)) {
w = wc;
} else {
result.add(dictionary.get(w));
dictionary.put(wc, dictSize++);
w = "" + c;
}
}
if (!w.isEmpty()) {
result.add(dictionary.get(w));
}
return result;
}
}