MCPcopy Create free account
hub / github.com/TheAlgorithms/Java / compress

Method compress

src/main/java/com/thealgorithms/compression/LZW.java:57–89  ·  view source on GitHub ↗

Compresses a string using the LZW algorithm. @param uncompressed The string to be compressed. Can be null. @return A list of integers representing the compressed data. Returns an empty list if the input is null or empty.

(String uncompressed)

Source from the content-addressed store, hash-verified

55 * list if the input is null or empty.
56 */
57 public static List<Integer> compress(String uncompressed) {
58 if (uncompressed == null || uncompressed.isEmpty()) {
59 return new ArrayList<>();
60 }
61
62 // Initialize dictionary with single characters (ASCII 0-255)
63 int dictSize = 256;
64 Map<String, Integer> dictionary = new HashMap<>();
65 for (int i = 0; i < dictSize; i++) {
66 dictionary.put("" + (char) i, i);
67 }
68
69 String w = "";
70 List<Integer> result = new ArrayList<>();
71 for (char c : uncompressed.toCharArray()) {
72 String wc = w + c;
73 if (dictionary.containsKey(wc)) {
74 // If the new string is in the dictionary, extend the current string
75 w = wc;
76 } else {
77 // Otherwise, output the code for the current string
78 result.add(dictionary.get(w));
79 // Add the new string to the dictionary
80 dictionary.put(wc, dictSize++);
81 // Start a new current string
82 w = "" + c;
83 }
84 }
85
86 // Output the code for the last remaining string
87 result.add(dictionary.get(w));
88 return result;
89 }
90
91 /**
92 * Decompresses a list of integers back into a string using the LZW algorithm.

Calls 5

isEmptyMethod · 0.65
putMethod · 0.45
containsKeyMethod · 0.45
addMethod · 0.45
getMethod · 0.45