Compresses the input text using the LZ78 algorithm. @param text The input string to compress. Must not be null. @return A list of Token objects representing the compressed data.
(String text)
| 66 | * @return A list of {@link Token} objects representing the compressed data. |
| 67 | */ |
| 68 | public static List<Token> compress(String text) { |
| 69 | if (text == null || text.isEmpty()) { |
| 70 | return new ArrayList<>(); |
| 71 | } |
| 72 | |
| 73 | List<Token> compressedOutput = new ArrayList<>(); |
| 74 | TrieNode root = new TrieNode(); |
| 75 | int nextDictionaryIndex = 1; |
| 76 | |
| 77 | TrieNode currentNode = root; |
| 78 | int lastMatchedIndex = 0; |
| 79 | |
| 80 | for (int i = 0; i < text.length(); i++) { |
| 81 | char currentChar = text.charAt(i); |
| 82 | |
| 83 | if (currentNode.children.containsKey(currentChar)) { |
| 84 | currentNode = currentNode.children.get(currentChar); |
| 85 | lastMatchedIndex = currentNode.index; |
| 86 | } else { |
| 87 | // Output: (index of longest matching prefix, current character) |
| 88 | compressedOutput.add(new Token(lastMatchedIndex, currentChar)); |
| 89 | |
| 90 | TrieNode newNode = new TrieNode(); |
| 91 | newNode.index = nextDictionaryIndex++; |
| 92 | currentNode.children.put(currentChar, newNode); |
| 93 | |
| 94 | currentNode = root; |
| 95 | lastMatchedIndex = 0; |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | // Handle remaining phrase at end of input |
| 100 | if (currentNode != root) { |
| 101 | compressedOutput.add(new Token(lastMatchedIndex, END_OF_STREAM)); |
| 102 | } |
| 103 | |
| 104 | return compressedOutput; |
| 105 | } |
| 106 | |
| 107 | /** |
| 108 | * Decompresses a list of LZ78 tokens back into the original string. |