2024年11月25日总结

今天完成了前端对数据库一张表的增删部分,改查还有一些缺陷。还重新温习了一下哈夫曼树
import java.util.*;

class HuffmanNode implements Comparable {
char character;
int frequency;
HuffmanNode left, right;

public HuffmanNode(char character, int frequency) {
    this.character = character;
    this.frequency = frequency;
    this.left = this.right = null;
}

@Override
public int compareTo(HuffmanNode other) {
    return this.frequency - other.frequency;
}

}

public class HuffmanTree {
public static void main(String[] args) {
String input = "this is an example for huffman encoding";
Map<Character, Integer> frequencyMap = buildFrequencyMap(input);
HuffmanNode root = buildHuffmanTree(frequencyMap);
Map<Character, String> huffmanCodes = generateHuffmanCodes(root, "");

    System.out.println("Huffman Codes:");
    for (Map.Entry<Character, String> entry : huffmanCodes.entrySet()) {
        System.out.println(entry.getKey() + ": " + entry.getValue());
    }
}

private static Map<Character, Integer> buildFrequencyMap(String input) {
    Map<Character, Integer> frequencyMap = new HashMap<>();
    for (char c : input.toCharArray()) {
        frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
    }
    return frequencyMap;
}

private static HuffmanNode buildHuffmanTree(Map<Character, Integer> frequencyMap) {
    PriorityQueue<HuffmanNode> minHeap = new PriorityQueue<>();
    for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
        minHeap.add(new HuffmanNode(entry.getKey(), entry.getValue()));
    }

    while (minHeap.size() > 1) {
        HuffmanNode left = minHeap.poll();
        HuffmanNode right = minHeap.poll();
        HuffmanNode parent = new HuffmanNode('\\0', left.frequency + right.frequency);
        parent.left = left;
        parent.right = right;
        minHeap.add(parent);
    }

    return minHeap.poll();
}

private static Map<Character, String> generateHuffmanCodes(HuffmanNode root, String code) {
    Map<Character, String> huffmanCodes = new HashMap<>();
    if (root != null) {
        if (root.left == null && root.right == null) {
            huffmanCodes.put(root.character, code);
        }
        huffmanCodes.putAll(generateHuffmanCodes(root.left, code + "0"));
        huffmanCodes.putAll(generateHuffmanCodes(root.right, code + "1"));
    }
    return huffmanCodes;
}

}

posted @ 2024-11-25 23:25  离璨霂  阅读(3)  评论(0编辑  收藏  举报