考虑使用不同长度的 bit string
来编码不同的字符串,其中一种保证没有一个 bit string
对应两个及以上的字符串的编码叫做 prefix
codes(前缀码)。
prefix code
可以通过二叉树来表示,每一个树中的叶节点的标签即为对应的字符串,而一条连接
left child 的边的标签被指定为 ,对应的连接 right child 的边的标签为
。那么,一个字符串对应的 bit
string 为从根到该叶节点的唯一通路上的边的标签的序列。
例子
Kenneth Rosen - Discrete Mathematics and
Its Applications - 8th edition - Chapter 11.2 - Figure 5
对于这棵树,其中
对应的编码分别是
Huffman Coding
那么哈夫曼编码是什么呢?其实是为了解决生成一颗比较”好”的 Prefix
Tree,来实现更短的 bit string
编码长度,哈夫曼编码是一种基本的数据压缩算法,通过压缩编码长度,我们便能减小压缩文件的大小。
原理
先给出算法的伪代码
Kenneth Rosen - Discrete Mathematics and
Its Applications - 8th edition - Chapter 11.2 - Algorithm2
intencodingSize(string path = ""){ if (!left && !right) { return freq * path.length(); } int sum = 0; if (left) sum += left->encodingSize(path + "0"); if (right) sum += right->encodingSize(path + "1"); return sum; }
voidsolve(){ string str = "The pandemic of COVID is a test of social system"; vector<char> input; // 预处理:大写转小写,存入vector for (auto c : str) { if (isupper(c)) { c = tolower(c); } input.push_back(c); } // 编码并打印前序遍历的叶子节点 HuffmanEncoder(input); }