我正在编码霍夫曼代码,我导入一个文件,为每个字符生成霍夫曼代码,然后将二进制文件输出到文件中。要导入我正在使用读取每个字符的扫描程序的字符,请将其放入具有读取字符值和频率为1的节点中。然后,将该节点添加到PriorityQueue中。由于Node类有一个比较频率的compareTo方法,我如何为这个特定的PriorityQueue实现一个比较器,比较队列中排序时的字符?谢谢你提前。
字面示例: 字符队列应按如下方式排序:
[A:1][A:1][A:1][B:1][C:1]
Next step:
[A:1][A:2][B:1][C:1]
Final:
[A:3][B:1][C:1]
以下是一些片段:
protected class Node implements Comparable<Node>{
Character symbol;
int frequency;
Node left = null;
Node right = null;
@Override
public int compareTo(Node n) {
return n.frequency < this.frequency ? 1 : (n.frequency == this.frequency ? 0 : -1);
}
public Node(Character c, int f){
this.symbol = c;
this.frequency = f;
}
public String toString(){
return "["+this.symbol +","+this.frequency+"]";
}
这是需要自定义比较器的PriorityQueue:
public static PriorityQueue<Node> gatherFrequency(String file) throws Exception{
File f = new File(file);
Scanner reader = new Scanner(f);
PriorityQueue<Node> PQ = new PriorityQueue<Node>();
while(reader.hasNext()){
for(int i = 0; i < reader.next().length();i++){
PQ.add(new Node(reader.next().charAt(0),1));
}
}
if(PQ.size()>1){ //during this loop the nodes should be compared by character value
while(PQ.size() > 1){
Node a = PQ.remove();
Node b = PQ.remove();
if(a.symbol.compareTo(b.symbol)==0){
Node c = new Node(a.symbol, a.frequency + b.frequency);
PQ.add(c);
}
else break;
}
return PQ;
}
return PQ;
}
这是我使用HashMap创建的新方法:
public static Collection<Entry<Character,Integer>> gatherFrequency(String file) throws Exception{
File f = new File(file);
Scanner reader = new Scanner(f);
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
while(reader.hasNext()){
for(int i = 0; i < reader.next().length();i++){
Character key = reader.next().charAt(i);
if(map.containsKey(reader.next().charAt(i))){
int freq = map.get(key);
map.put(key, freq+1);
}
else{
map.put(key, 1);
}
}
}
return map.entrySet();
}
答案 0 :(得分:2)
实现Huffman树的标准方法是使用 hashmap (在Java中,您可能使用HashMap<Character, Integer>
)来计算每个字母的频率,并插入到优先级为每个字母排队一个节点。因此,在构建Huffman树本身时,您将从优先级队列开始,该队列已经处于您显示的“最终”状态。然后,Huffman算法从优先级队列中重复提取两个节点,为这两个节点构造一个新的父节点,并将新节点插入优先级队列。