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)
| 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. |