|
发表于 2024-6-6 22:48:43
|
显示全部楼层
下面是用C++实现的哈夫曼编码和译码的代码:
- #include <iostream>
- #include <string>
- #include <map>
- #include <queue>
- using namespace std;
- // 结点定义
- struct Node {
- char data;
- int freq;
- Node* left;
- Node* right;
-
- Node(char data, int freq) : data(data), freq(freq), left(nullptr), right(nullptr) {}
- };
- // 优先队列比较函数
- struct Compare {
- bool operator()(Node* left, Node* right) {
- return left->freq > right->freq;
- }
- };
- // 哈夫曼编码
- class Huffman {
- private:
- map<char, string> codes;
- Node* root;
- // 建立哈夫曼树
- Node* buildTree(map<char, int>& freqMap) {
- priority_queue<Node*, vector<Node*>, Compare> pq;
- for (auto& pair : freqMap) {
- Node* newNode = new Node(pair.first, pair.second);
- pq.push(newNode);
- }
- while (pq.size() > 1) {
- Node* left = pq.top(); pq.pop();
- Node* right = pq.top(); pq.pop();
- Node* parent = new Node('$', left->freq + right->freq);
- parent->left = left;
- parent->right = right;
- pq.push(parent);
- }
- return pq.top();
- }
- // 生成编码
- void generateCodes(Node* root, string code) {
- if (!root) return;
- if (root->data != '$') {
- codes[root->data] = code;
- }
- generateCodes(root->left, code + "0");
- generateCodes(root->right, code + "1");
- }
- public:
- Huffman(map<char, int>& freqMap) {
- root = buildTree(freqMap);
- generateCodes(root, "");
- }
- // 获取编码
- string encode(string text) {
- string encoded = "";
- for (char c : text) {
- encoded += codes[c];
- }
- return encoded;
- }
- // 获取译码
- string decode(string encodedText) {
- string decoded = "";
- Node* current = root;
- for (char bit : encodedText) {
- if (bit == '0') {
- current = current->left;
- } else {
- current = current->right;
- }
- if (current->data != '$') {
- decoded += current->data;
- current = root;
- }
- }
- return decoded;
- }
- };
- int main() {
- string text = "I went to a lot of place. Disneyland park and summer holiday. I made some new friends. Do you know who they are? Let me tell you, they are my favorite books. I like books very much, like reading science books, English books, Chinese books, cartoon books, and so on.";
- map<char, int> freqMap;
- for (char c : text) {
- if (isalpha(c)) {
- c = tolower(c);
- freqMap[c]++;
- }
- }
- Huffman huffman(freqMap);
- string encodedText = huffman.encode(text);
- cout << "Encoded Text: " << encodedText << endl;
- string decodedText = huffman.decode(encodedText);
- cout << "Decoded Text: " << decodedText << endl;
- return 0;
- }
复制代码
这段代码实现了对给定文本进行哈夫曼编码和译码。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|