Decompresses a list of LZ78 tokens back into the original string. @param compressedData The list of Token objects. Must not be null. @return The original, uncompressed string.
(List<Token> compressedData)
| 111 | * @return The original, uncompressed string. |
| 112 | */ |
| 113 | public static String decompress(List<Token> compressedData) { |
| 114 | if (compressedData == null || compressedData.isEmpty()) { |
| 115 | return ""; |
| 116 | } |
| 117 | |
| 118 | StringBuilder decompressedText = new StringBuilder(); |
| 119 | Map<Integer, String> dictionary = new HashMap<>(); |
| 120 | int nextDictionaryIndex = 1; |
| 121 | |
| 122 | for (Token token : compressedData) { |
| 123 | String prefix = (token.index == 0) ? "" : dictionary.get(token.index); |
| 124 | |
| 125 | if (token.nextChar == END_OF_STREAM) { |
| 126 | decompressedText.append(prefix); |
| 127 | } else { |
| 128 | String currentPhrase = prefix + token.nextChar; |
| 129 | decompressedText.append(currentPhrase); |
| 130 | dictionary.put(nextDictionaryIndex++, currentPhrase); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | return decompressedText.toString(); |
| 135 | } |
| 136 | } |