哈弗曼编码加密程序Decoder

package 哈弗曼编码;
import java.util.*;

public class Decoder {
	private String binCode;
	private BinaryNode root;
	private HashMap<String, Character> newDic=new HashMap<String, Character>();//解码时要根据二进制码的值得到字符,因此新的字典要以String作为Key
	private StringBuffer result=new StringBuffer();
	
	public Decoder(){
		
	}
	
	public Decoder(String binCode, BinaryNode root){
		this.binCode=binCode;
		
		decode(binCode,root);
	}
	
	public Decoder(String binCode, HashMap<Character,String> dic){
		this.binCode=binCode;
		decode(binCode,dic);
	}
	
	public void decode(String binCode, BinaryNode root){
		this.binCode=binCode;
		
		//构建编码字典,以HashMap结构存储。
		if(root.left==null&&root.right==null){
			newDic.put("0",root.data.getStr().charAt(0));
		}
		else{
			generateBinCode(root,"");
		}
		
		decode();
	}
	
	public void decode(String binCode, HashMap<Character,String> dic){
		this.binCode=binCode;
		//得到dic的keySet,遍历其中的key,然后构造newDic。
		for(Character key:dic.keySet()){
			newDic.put(dic.get(key), key);
		}
		
		for(String bc:newDic.keySet()){
			System.out.print(bc+": "+newDic.get(bc));
			System.out.println();
		}
		
		decode();
		
	}
	
	private void decode(){
		if(binCode==null||newDic==null){
			System.out.println("Please specify the binary code and dictionary or huffman tree root");
			return;
		}
		else if(validate()==false){
			System.out.println("The binCode is invalidate!");
		}
		else{
//			System.out.println("here");
			StringBuffer search=new StringBuffer();
			
			for(int i=0;i<binCode.length();i++){
				search.append(binCode.charAt(i));
				if(newDic.containsKey(search.toString())){
					result.append(newDic.get(search.toString()));
					search=new StringBuffer("");
				}
				
			}
			
			if(!search.toString().equals("")){
				result.append(" ERROR");
			}
			
			
		}
	}
	
	//该方法将验证binCode是否为只含0,1的有效编码。
	public boolean validate(){
		char ch;
		for(int i=0;i<binCode.length();i++){
			if((ch=binCode.charAt(i))!='0'&&ch!='1'){
				return false;
			}
		}
		return true;
	}
	
	private void generateBinCode(BinaryNode node, String str){
		if(node.left==null&&node.right==null){
			newDic.put(str,node.data.getStr().charAt(0));
			return;
		}
		else{
			generateBinCode(node.left,str+"0");
			generateBinCode(node.right,str+"1");
		}
	}
	
	public String getResult(){
		return result.toString();
	}
	
	public static void main(String[] str){
		Encoder ec=new Encoder();
		ec.encode("hello neilli! will this work!!!");
		System.out.println(ec.getBinCode());
		
		Decoder dc=new Decoder();
		dc.decode(ec.getBinCode(), ec.getRoot());
//		dc.decode(ec.getBinCode(), ec.getDic());
		System.out.println(dc.getResult());
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值