一、Huffman压缩:
public class Huffman
{
private static int R = 256;
private static class Node implements Comparable<Node>
{
private Node left, right;
private int freq;
private char ch;
Node(char ch, int freq, Node left, Node right)
{
this.ch = ch;
this.freq = freq;
this.left = left;
this.right = right;
}
public boolean isLeaf()
{
return left == null && right == null;
}
@Override
public int compareTo(Node that)
{
// TODO Auto-generated method stub
return this.freq - that.freq;
}
}
public static void expand()
{
Node root = readTriel();
int N = BinaryStdIn.readInt();
for (int i = 0; i < N; i++)
{
Node x = root;
while(!x.isLeaf())
{
if(BinaryStdIn.readBoolean())
x = x.right;
else x = x.left;
}
BinaryStdOut.write(x.ch);
}
BinaryStdOut.close();
}
public static void compress()
{
String s = BinaryStdIn.readStrin();
char[] input = s.toCharArray();
int[] freq = new int[R];
for (int i = 0; i < input.length; i++)
freq[input[i]]++;
Node root = buildTrie(freq);
String[] st = new String[R];
buildCode(st, root, "");
writeTrie(root);
BinaryStdOut.write(input.length);
for (int i = 0; i < input.length; i++)
{
String code = st[input[i]];
for (int j = 0; j < code.length(); j++)
if(code.charAt(j) == "1")
BinaryStdOut.write(true);
else
BinaryStdOut.write(false);
}
BinaryStdOut.close();
}
}
二、LZW算法:
public class LZW
{
private static int R = 256;
private static int L = 4096;
private static int W = 12;
public static void compress()
{
String input = BinaryStdIn.readString();
TST<Integer> st = new TST<Integer>();
for (int i = 0; i < R; i++)
st.put("" + (char)i, i);
int count = R + 1;
while (input.length() > 0)
{
String s = st.longestPrefix(input);
BinaryStdOut.write(st.get(s), W);
int t = s.length();
if (t < input.length() && code < L)
st.put(input.substring(0, t + 1), count++);
input = input.substring(t);
}
BinaryStdOut.write(R, W);
BinaryStdOut.close();
}
public static void expand()
{
String[] st = new String[L];
int i;
for (i = 0; i < R; i++)
st[i] = "" + (char)i;
st[i++] = "";
int codeword = BinaryStdIn.readInt(W);
String val = st[codeword];
while(true)
{
BinaryStdOut.write(val);
codeword = BinaryStdIn.readInt(W);
if (codeword == R) return;
String s = st[codeword];
if (codeword == i)
s = val + val.charAt(0);
if (codeword < L)
st[i++] = val + s.charAt(0);
val = s;
}
BinaryStdOut.close();
}
}