1. 程式人生 > >哈弗曼編碼的java實現

哈弗曼編碼的java實現

import java.util.*;

/**
 * Created by lipu on 17-6-28.
 */

class Node {
    Character c;
    int power;
    Node left = null;
    Node right = null;
    boolean isC = false;

    String s = null;

    Node(Character c, int power, Node left, Node right, boolean isC) {
        this.c = c;
        this
.power = power; this.left = left; this.right = right; this.isC = isC; } int getPower() { return power; } void putString(String s) { this.s = s; } } public class huffman { public static void main(String[] args) { PriorityQueue<Node> q = new
PriorityQueue<Node>(100, new Comparator<Node>() { @Override public int compare(Node n1, Node n2) { return n1.getPower() - n2.getPower(); } }); String s = "beep boop beer!"; Map<Character, Integer> m = new HashMap<>(); for
(int i = 0; i < s.length(); i++) { if (m.get(s.charAt(i)) != null) { m.put(s.charAt(i), m.get(s.charAt(i)) + 1);//= =蘭黛嗎 } else { m.put(s.charAt(i), 1); } } for (char fuck : m.keySet()) { q.add(new Node(fuck, m.get(fuck), null, null, false)); }//優先佇列已按照power大小儲存完畢 while (q.size() != 1) { Node a = q.remove(); Node b = q.remove(); Node c = new Node(null, a.getPower() + b.getPower(), a, b, true); q.add(c); } Node root = q.remove();//root即為整個二叉樹的根節點 System.out.println(root.getPower()); Map<Character, String> res = new HashMap<>(); Queue<Node> floor = new LinkedList<>(); Node a = root.left; a.putString("0"); Node b = root.right; b.putString("1"); floor.add(a); floor.add(b); while (!floor.isEmpty()) { Node x = floor.remove(); if (x.left == null) {//如果是子節點,就表明這是要存到結果裡的節點(根據哈弗曼數的性質,左子樹為空則右子樹一定為空) res.put(x.c, x.s); } else {//如果不是子節點 x.left.putString(x.s + "0"); floor.add(x.left); x.right.putString(x.s + "1"); floor.add(x.right); } } for (Character c : res.keySet()) { System.out.print(c + " : "); System.out.println(res.get(c)); } } }