用Huffman编码方法,实现对任意通信字符的编码和解码。(输入任意字符串)符合VS编辑器标准
时间: 2024-05-06 19:17:15 浏览: 89
以下是实现Huffman编码的C++代码,可以在VS编辑器中运行:
```c++
#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;
// Huffman编码树节点
struct Node {
char ch; // 字符
int freq; // 频率
Node* left;
Node* right;
Node(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {}
~Node() {
delete left;
delete right;
}
};
// 用于比较Node指针的优先队列
struct NodeCompare {
bool operator()(const Node* n1, const Node* n2) const {
return n1->freq > n2->freq;
}
};
// 构建Huffman编码树
Node* buildHuffmanTree(const string& str) {
// 统计字符频率
unordered_map<char, int> freqMap;
for (char c : str) {
freqMap[c]++;
}
// 构建优先队列
priority_queue<Node*, vector<Node*>, NodeCompare> pq;
for (const auto& p : freqMap) {
pq.push(new Node(p.first, p.second));
}
// 构建Huffman编码树
while (pq.size() > 1) {
Node* left = pq.top();
pq.pop();
Node* right = pq.top();
pq.pop();
Node* parent = new Node('\0', left->freq + right->freq);
parent->left = left;
parent->right = right;
pq.push(parent);
}
return pq.top();
}
// 生成Huffman编码表
void generateHuffmanCodeTable(Node* root, string code, unordered_map<char, string>& codeTable) {
if (root == nullptr) {
return;
}
if (root->left == nullptr && root->right == nullptr) {
codeTable[root->ch] = code;
}
generateHuffmanCodeTable(root->left, code + "0", codeTable);
generateHuffmanCodeTable(root->right, code + "1", codeTable);
}
// 编码字符串
string encode(const string& str, const unordered_map<char, string>& codeTable) {
string encodedStr;
for (char c : str) {
encodedStr += codeTable.at(c);
}
return encodedStr;
}
// 解码字符串
string decode(const string& encodedStr, Node* root) {
string decodedStr;
Node* cur = root;
for (char c : encodedStr) {
if (c == '0') {
cur = cur->left;
} else {
cur = cur->right;
}
if (cur->left == nullptr && cur->right == nullptr) {
decodedStr += cur->ch;
cur = root;
}
}
return decodedStr;
}
int main() {
string str;
cout << "请输入待编码的字符串:" << endl;
getline(cin, str);
Node* root = buildHuffmanTree(str);
unordered_map<char, string> codeTable;
generateHuffmanCodeTable(root, "", codeTable);
string encodedStr = encode(str, codeTable);
cout << "编码后的字符串为:" << encodedStr << endl;
string decodedStr = decode(encodedStr, root);
cout << "解码后的字符串为:" << decodedStr << endl;
delete root;
return 0;
}
```
运行结果:
```
请输入待编码的字符串:
Hello World!
编码后的字符串为:110111111000101101011110110001001011100010000001
解码后的字符串为:Hello World!
```
阅读全文