实现huffman编码的小程序

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.TreeMap;

class nodecomparator implements Comparator<node>{
	public int compare(node x, node y)
    {
        if (x.val < y.val)
            return -1;
        if (x.val > y.val)
            return 1;
        return 0;
    }
}

public class test {
	//make the hash map
	public static Map<Character, Integer> makemap(String str) {
		Map<Character, Integer> m = new TreeMap<Character, Integer>();
		int n = str.length();
		for(int i = 0; i < n; i++) {
			Character tmp = str.charAt(i);
			if(!Character.isLetter(tmp)) continue;
			Integer freq = m.get(tmp);
			m.put(tmp, freq == null ? 1: freq + 1);
		}
		return m;
	}
	
<span style="white-space:pre">	</span>//generate the hash tree
	public static node maketree(LinkedList<node> list) {
		Comparator<node> com = new nodecomparator();
		do {
			node a = list.poll();
			node b = list.poll();
			list.add(new node(a.val+b.val, a, b));
			Collections.sort(list, com);
		}while(list.size() != 1);
		return list.poll();
	}
	
<span style="white-space:pre">	</span>//generate the hash code for each letter
	public static void makecode(node head, String str,ArrayList<String> ans) {
		if(head.isleaf) {ans.add(str+head.ch);return;}
		else{
		makecode(head.left, "0" + str, ans);
		makecode(head.right, "1" + str, ans);
		}
	}
	
	public static void printtree(node a) {
		if(a == null) return;
		System.out.println(a.val);
		printtree(a.left);
		printtree(a.right);
	}
	
	
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Map<Character, Integer> t = makemap("aaaaffabbb ,.bii");
		Iterator<?> it = t.entrySet().iterator();
		Comparator<node> com = new nodecomparator();
		List<node> list = new LinkedList<node>();
		while(it.hasNext()) {
			Map.Entry pair = (Map.Entry)it.next();
			list.add(new node((Integer)pair.getValue(), (Character)pair.getKey(), true));
			
		}
		Collections.sort(list,com);
		node head = maketree((LinkedList<node>) list);
		ArrayList<String> a = new ArrayList<String>();
		makecode(head, "",a);
		for(String c: a) {
			System.out.println(c);
		}
	}
	
	

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值