|
| 1 | +package com.thealgorithms.compression; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * An implementation of the Lempel-Ziv 77 (LZ77) compression algorithm. |
| 8 | + * <p> |
| 9 | + * LZ77 is a lossless data compression algorithm that works by finding repeated |
| 10 | + * occurrences of data in a sliding window. It replaces subsequent occurrences |
| 11 | + * with references (offset, length) to the first occurrence within the window. |
| 12 | + * </p> |
| 13 | + * <p> |
| 14 | + * This implementation uses a simple sliding window and lookahead buffer approach. |
| 15 | + * Output format is a sequence of tuples (offset, length, next_character). |
| 16 | + * </p> |
| 17 | + * <p> |
| 18 | + * Time Complexity: O(n*W) in this naive implementation, where n is the input length |
| 19 | + * and W is the window size, due to the search for the longest match. More advanced |
| 20 | + * data structures (like suffix trees) can improve this. |
| 21 | + * </p> |
| 22 | + * <p> |
| 23 | + * References: |
| 24 | + * <ul> |
| 25 | + * <li><a href="https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77">Wikipedia: LZ77</a></li> |
| 26 | + * </ul> |
| 27 | + * </p> |
| 28 | + */ |
| 29 | +public final class LZ77 { |
| 30 | + |
| 31 | + private static final int DEFAULT_WINDOW_SIZE = 4096; |
| 32 | + private static final int DEFAULT_LOOKAHEAD_BUFFER_SIZE = 16; |
| 33 | + private static final char END_OF_STREAM = '\u0000'; |
| 34 | + private LZ77() { |
| 35 | + } |
| 36 | + |
| 37 | + /** |
| 38 | + * Represents a token in the LZ77 compressed output. |
| 39 | + * Stores the offset back into the window, the length of the match, |
| 40 | + * and the next character after the match (or END_OF_STREAM if at end). |
| 41 | + */ |
| 42 | + public record Token(int offset, int length, char nextChar) { |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Compresses the input text using the LZ77 algorithm. |
| 47 | + * |
| 48 | + * @param text The input string to compress. Must not be null. |
| 49 | + * @param windowSize The size of the sliding window (search buffer). Must be positive. |
| 50 | + * @param lookaheadBufferSize The size of the lookahead buffer. Must be positive. |
| 51 | + * @return A list of {@link Token} objects representing the compressed data. |
| 52 | + * @throws IllegalArgumentException if windowSize or lookaheadBufferSize are not positive. |
| 53 | + */ |
| 54 | + public static List<Token> compress(String text, int windowSize, int lookaheadBufferSize) { |
| 55 | + if (text == null) { |
| 56 | + return new ArrayList<>(); |
| 57 | + } |
| 58 | + if (windowSize <= 0 || lookaheadBufferSize <= 0) { |
| 59 | + throw new IllegalArgumentException("Window size and lookahead buffer size must be positive."); |
| 60 | + } |
| 61 | + |
| 62 | + List<Token> compressedOutput = new ArrayList<>(); |
| 63 | + int currentPosition = 0; |
| 64 | + |
| 65 | + while (currentPosition < text.length()) { |
| 66 | + int bestMatchDistance = 0; |
| 67 | + int bestMatchLength = 0; |
| 68 | + |
| 69 | + // Define the start of the search window |
| 70 | + int searchBufferStart = Math.max(0, currentPosition - windowSize); |
| 71 | + // Define the end of the lookahead buffer (don't go past text length) |
| 72 | + int lookaheadEnd = Math.min(currentPosition + lookaheadBufferSize, text.length()); |
| 73 | + |
| 74 | + // Search for the longest match in the window |
| 75 | + for (int i = searchBufferStart; i < currentPosition; i++) { |
| 76 | + int currentMatchLength = 0; |
| 77 | + |
| 78 | + // Check how far the match extends into the lookahead buffer |
| 79 | + // This allows for overlapping matches (e.g., "aaa" can match with offset 1) |
| 80 | + while (currentPosition + currentMatchLength < lookaheadEnd) { |
| 81 | + int sourceIndex = i + currentMatchLength; |
| 82 | + |
| 83 | + // Handle overlapping matches (run-length encoding within LZ77) |
| 84 | + // When we've matched beyond our starting position, wrap around using modulo |
| 85 | + if (sourceIndex >= currentPosition) { |
| 86 | + int offset = currentPosition - i; |
| 87 | + sourceIndex = i + (currentMatchLength % offset); |
| 88 | + } |
| 89 | + |
| 90 | + if (text.charAt(sourceIndex) == text.charAt(currentPosition + currentMatchLength)) { |
| 91 | + currentMatchLength++; |
| 92 | + } else { |
| 93 | + break; |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + // If this match is longer than the best found so far |
| 98 | + if (currentMatchLength > bestMatchLength) { |
| 99 | + bestMatchLength = currentMatchLength; |
| 100 | + bestMatchDistance = currentPosition - i; // Calculate offset from current position |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + char nextChar; |
| 105 | + if (currentPosition + bestMatchLength < text.length()) { |
| 106 | + nextChar = text.charAt(currentPosition + bestMatchLength); |
| 107 | + } else { |
| 108 | + nextChar = END_OF_STREAM; |
| 109 | + } |
| 110 | + |
| 111 | + // Add the token to the output |
| 112 | + compressedOutput.add(new Token(bestMatchDistance, bestMatchLength, nextChar)); |
| 113 | + |
| 114 | + // Move the current position forward |
| 115 | + // If we're at the end and had a match, just move by the match length |
| 116 | + if (nextChar == END_OF_STREAM) { |
| 117 | + currentPosition += bestMatchLength; |
| 118 | + } else { |
| 119 | + currentPosition += bestMatchLength + 1; |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + return compressedOutput; |
| 124 | + } |
| 125 | + |
| 126 | + /** |
| 127 | + * Compresses the input text using the LZ77 algorithm with default buffer sizes. |
| 128 | + * |
| 129 | + * @param text The input string to compress. Must not be null. |
| 130 | + * @return A list of {@link Token} objects representing the compressed data. |
| 131 | + */ |
| 132 | + public static List<Token> compress(String text) { |
| 133 | + return compress(text, DEFAULT_WINDOW_SIZE, DEFAULT_LOOKAHEAD_BUFFER_SIZE); |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * Decompresses a list of LZ77 tokens back into the original string. |
| 138 | + * |
| 139 | + * @param compressedData The list of {@link Token} objects. Must not be null. |
| 140 | + * @return The original, uncompressed string. |
| 141 | + */ |
| 142 | + public static String decompress(List<Token> compressedData) { |
| 143 | + if (compressedData == null) { |
| 144 | + return ""; |
| 145 | + } |
| 146 | + |
| 147 | + StringBuilder decompressedText = new StringBuilder(); |
| 148 | + |
| 149 | + for (Token token : compressedData) { |
| 150 | + // Copy matched characters from the sliding window |
| 151 | + if (token.length > 0) { |
| 152 | + int startIndex = decompressedText.length() - token.offset; |
| 153 | + |
| 154 | + // Handle overlapping matches (e.g., when length > offset) |
| 155 | + for (int i = 0; i < token.length; i++) { |
| 156 | + decompressedText.append(decompressedText.charAt(startIndex + i)); |
| 157 | + } |
| 158 | + } |
| 159 | + |
| 160 | + // Append the next character (if not END_OF_STREAM) |
| 161 | + if (token.nextChar != END_OF_STREAM) { |
| 162 | + decompressedText.append(token.nextChar); |
| 163 | + } |
| 164 | + } |
| 165 | + |
| 166 | + return decompressedText.toString(); |
| 167 | + } |
| 168 | +} |
0 commit comments