要求
编码:输入一段文本,利用霍夫曼编码对其进行压缩编码,首先需要计算各字符的频率并保存在文本中,然后根据该文本建立霍夫曼树,确定各字符对应的霍夫曼编码。
输入:
解码:输入一段由0和1组成的编码后的文本,利用建立的霍夫曼编码表将其还原成编码前的文本信息。
分析
- 统计给定文档的每个字符的频数并存储下来
- 根据所统计的信息建立霍夫曼树
- 得到每个字符的编码
- 再根据编码解压缩编码得到文本
代码
#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <fstream>
#include <sstream>
#include <algorithm>
using namespace std;
struct Node //霍夫曼节点类 包括:存储的字符 频率 编码
{
char content;
int freq;
string code;
Node *left;
Node *right;
Node(){left=right=NULL;};
};
bool compare(Node* a,Node* b)
{
return a->freq>b->freq; //按照降序排列 自定义sort的排序方法
}
class HolfTree
{
private:
Node *root;
void OutPutToStream(Node* p);
void OutToFileStream(Node * node,string &str,int depth);
string NumToStr(int num);
public:
HolfTree(){root=new Node();};
void BulidTree(string filename);
void OutPut();