[英]Where does my Huffman encoding method go wrong?
我正在嘗試編寫霍夫曼字符串編碼算法。
我的解決方案是這樣工作的:
我沒有在某處打印樹,即使它可以幫助你幫助我,但這是我從字符串abracadabra得到的,以及我應該得到的:
正確代碼: 000010000110110101111101011000111110110100111011101100101101110000110000110111100101111101010010
我得到的是: 00001000111011010110101111010101100011101011010
這是我的代碼:
#include <algorithm>
#include <map>
string codes = "";
void getMapCharBinaryCode(Node root, string &prefix, map <char, string> &m){
if(!root) return;
if(root->value){
if(!m.count(root->value)){
m[root->value] = prefix;
prefix = "";
}
}
if(root->leftChild){
getMapCharBinaryCode(root->leftChild, prefix += "0",m);
}
if(root->rightChild){
getMapCharBinaryCode(root->rightChild, prefix += "1",m);
}
}
string encode(string text, Node tree){
// text is "abracadabra"
// create map for each char -> binary code
map<char, string> m;
string prefix = "";
getMapCharBinaryCode(tree, prefix, m);
// iterate on text and assign each letter with binary code from map
for(int i = 0; i < text.size(); i++) {
codes += m[text[i]];
}
return codes;
}
當您使用prefix = ""
保存葉子時,您正在破壞prefix
中的代碼,在返回樹並轉到下一個分支時需要代碼。
您可以為prefix
維護一個單獨的存儲區域,通過引用傳遞它。 然而,你需要管理的長度prefix
,你去向上和向下的樹,你需要不加一個0
,然后添加一個1
到兩個分支,加入01
的右支,而不是1
。
作為起點,您應該只按值傳遞prefix
,這會進行復制,但不需要管理。 去掉&
並將prefix +=
替換為prefix +
。 去掉prefix = ""
,然后它什么都不做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.