数据压缩

一、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();
		
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值