/****************************************************************************** * Compilation: javac LZW.java * Execution: java LZW - < input.txt (compress) * Execution: java LZW + < input.txt (expand) * Dependencies: BinaryIn.java BinaryOut.java * Data files: https://algs4.cs.princeton.edu/55compression/abraLZW.txt * https://algs4.cs.princeton.edu/55compression/ababLZW.txt * * Compress or expand binary input from standard input using LZW. * ******************************************************************************/ /** * The {@code LZW} class provides static methods for compressing * and expanding a binary input using LZW compression over the 8-bit extended * ASCII alphabet with 12-bit codewords. *
* WARNING: Starting with Oracle Java 7u6, the substring method takes time and * space linear in the length of the extracted substring (instead of constant * time an space as in earlier versions). As a result, compression takes * quadratic time. TODO: fix. * See this article * for more details. *
* For additional documentation,
* see Section 5.5 of
* Algorithms, 4th Edition by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
public class LZW {
private static final int R = 256; // number of input chars
private static final int L = 4096; // number of codewords = 2^W
private static final int W = 12; // codeword width
// Do not instantiate.
private LZW() { }
/**
* Reads a sequence of 8-bit bytes from standard input; compresses
* them using LZW compression with 12-bit codewords; and writes the results
* to standard output.
*/
public static void compress() {
String input = BinaryStdIn.readString();
TST