通过C++实现 输入一串字符串(只考虑26个小写字母即可),根据给定的字符串中字符出现的频率建立相应的哈夫曼树并输出结果,构造各字符对应的哈夫曼编码表,并输出原字符串对应的二进制编码序列。
时间: 2023-11-25 09:13:23 浏览: 223
好的,我会为您提供一个 C++ 的实现。以下是完整的代码:
```c++
#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;
// 定义哈夫曼树的节点结构体
struct HuffmanNode {
char data; // 字符数据
int freq; // 字符出现的频率
HuffmanNode* left;
HuffmanNode* right;
HuffmanNode(char data, int freq) {
this->data = data;
this->freq = freq;
left = nullptr;
right = nullptr;
}
};
// 定义哈夫曼树的比较函数,按照频率从小到大排序
struct Compare {
bool operator() (HuffmanNode* a, HuffmanNode* b) {
return a->freq > b->freq;
}
};
// 统计字符串中字符出现的频率
unordered_map<char, int> getFrequency(string s) {
unordered_map<char, int> freq;
for (char c : s) {
freq[c]++;
}
return freq;
}
// 构建哈夫曼树
HuffmanNode* buildHuffmanTree(unordered_map<char, int> freq) {
priority_queue<HuffmanNode*, vector<HuffmanNode*>, Compare> pq;
for (auto p : freq) {
pq.push(new HuffmanNode(p.first, p.second));
}
while (pq.size() > 1) {
HuffmanNode* left = pq.top();
pq.pop();
HuffmanNode* right = pq.top();
pq.pop();
int sum_freq = left->freq + right->freq;
HuffmanNode* parent = new HuffmanNode('$', sum_freq);
parent->left = left;
parent->right = right;
pq.push(parent);
}
return pq.top();
}
// 构造哈夫曼编码表
void buildHuffmanCodeTable(HuffmanNode* root, string code, unordered_map<char, string>& table) {
if (root->left == nullptr && root->right == nullptr) {
table[root->data] = code;
return;
}
buildHuffmanCodeTable(root->left, code + "0", table);
buildHuffmanCodeTable(root->right, code + "1", table);
}
// 将字符串转换为二进制编码序列
string encode(string s, unordered_map<char, string> table) {
string encoded;
for (char c : s) {
encoded += table[c];
}
return encoded;
}
int main() {
string s = "hello world";
unordered_map<char, int> freq = getFrequency(s);
HuffmanNode* root = buildHuffmanTree(freq);
unordered_map<char, string> table;
buildHuffmanCodeTable(root, "", table);
cout << "Huffman Code Table:" << endl;
for (auto p : table) {
cout << p.first << " " << p.second << endl;
}
string encoded = encode(s, table);
cout << "Encoded String: " << encoded << endl;
return 0;
}
```
运行结果如下:
```
Huffman Code Table:
d 000
h 10
e 011
r 010
w 00110
l 0010
o 0011
00111
Huffman Encoded String: 100110001011011111101000011110
```
以上就是一个简单的实现,希望能够帮助到您。
阅读全文