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

Method compress

src/main/java/com/thealgorithms/compression/LZ78.java:68–105  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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.

Callers 15

testStandardExampleMethod · 0.95
testLongerExampleMethod · 0.95
testEmptyStringMethod · 0.95
testAllSameCharactersMethod · 0.95
testSingleCharacterMethod · 0.95
testTwoCharactersMethod · 0.95
testRepeatingPairsMethod · 0.95
testGrowingPatternsMethod · 0.95

Calls 6

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

Tested by 15

testStandardExampleMethod · 0.76
testLongerExampleMethod · 0.76
testEmptyStringMethod · 0.76
testAllSameCharactersMethod · 0.76
testSingleCharacterMethod · 0.76
testTwoCharactersMethod · 0.76
testRepeatingPairsMethod · 0.76
testGrowingPatternsMethod · 0.76