哈夫曼编码实现的代码
时间: 2023-12-11 09:30:21 浏览: 76
哈夫曼编码是一种常用的数据压缩算法,它可以将一些出现频率较高的字符用较短的编码表示,从而达到压缩数据的目的。下面是一个简单的C++实现:
```c++
#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;
// 定义哈夫曼树节点
struct HuffmanNode {
char ch; // 字符
int freq; // 频率
HuffmanNode *left, *right; // 左右子节点
HuffmanNode(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {}
};
// 定义哈夫曼树节点比较函数
struct Compare {
bool operator()(HuffmanNode* a, HuffmanNode* b) {
return a->freq > b->freq;
}
};
// 构建哈夫曼树
HuffmanNode* buildHuffmanTree(const string& str) {
// 统计字符频率
unordered_map<char, int> freqMap;
for (char c : str) {
freqMap[c]++;
}
// 构建哈夫曼树
priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq;
for (auto& p : freqMap) {
pq.push(new HuffmanNode(p.first, p.second));
}
while (pq.size() > 1) {
HuffmanNode* left = pq.top();
pq.pop();
HuffmanNode* right = pq.top();
pq.pop();
HuffmanNode* parent = new HuffmanNode('\0', left->freq + right->freq);
parent->left = left;
parent->right = right;
pq.push(parent);
}
return pq.top();
}
// 生成哈夫曼编码表
void generateHuffmanCodeTable(HuffmanNode* root, string code, unordered_map<char, string>& codeTable) {
if (!root) {
return;
}
if (root->ch != '\0') {
codeTable[root->ch] = code;
}
generateHuffmanCodeTable(root->left, code + "0", codeTable);
generateHuffmanCodeTable(root->right, code + "1", codeTable);
}
// 哈夫曼编码
string huffmanEncode(const string& str) {
// 构建哈夫曼树
HuffmanNode* root = buildHuffmanTree(str);
// 生成哈夫曼编码表
unordered_map<char, string> codeTable;
generateHuffmanCodeTable(root, "", codeTable);
// 哈夫曼编码
string encodedStr;
for (char c : str) {
encodedStr += codeTable[c];
}
return encodedStr;
}
// 哈夫曼解码
string huffmanDecode(const string& str, HuffmanNode* root) {
string decodedStr;
HuffmanNode* cur = root;
for (char c : str) {
if (c == '0') {
cur = cur->left;
} else {
cur = cur->right;
}
if (cur->ch != '\0') {
decodedStr += cur->ch;
cur = root;
}
}
return decodedStr;
}
int main() {
string str = "hello world";
string encodedStr = huffmanEncode(str);
cout << "Encoded string: " << encodedStr << endl;
HuffmanNode* root = buildHuffmanTree(str);
string decodedStr = huffmanDecode(encodedStr, root);
cout << "Decoded string: " << decodedStr << endl;
return 0;
}
```
阅读全文