-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhuffman.cpp
85 lines (74 loc) · 1.69 KB
/
huffman.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "huffman.h"
#include <queue>
#include <vector>
#include <iostream>
struct compare
{
bool operator()(Node *l, Node *r)
{
return l->freq > r->freq;
}
};
void HuffmanCoding::buildTree(const std::string &text)
{
std::unordered_map<char, int> freq;
for (char ch : text)
{
freq[ch]++;
}
std::priority_queue<Node *, std::vector<Node *>, compare> minHeap;
for (auto pair : freq)
{
minHeap.push(new Node(pair.first, pair.second));
}
while (minHeap.size() != 1)
{
Node *left = minHeap.top();
minHeap.pop();
Node *right = minHeap.top();
minHeap.pop();
int sum = left->freq + right->freq;
Node *newNode = new Node('\0', sum);
newNode->left = left;
newNode->right = right;
minHeap.push(newNode);
}
root = minHeap.top();
buildCode(root, "");
}
void HuffmanCoding::buildCode(Node *node, const std::string &str)
{
if (!node)
return;
if (node->ch != '\0')
{
codes[node->ch] = str;
reverseCodes[str] = node->ch;
}
buildCode(node->left, str + "0");
buildCode(node->right, str + "1");
}
std::string HuffmanCoding::encode(const std::string &text)
{
std::string encodedStr;
for (char ch : text)
{
encodedStr += codes[ch];
}
return encodedStr;
}
std::string HuffmanCoding::decode(const std::string &encodedStr)
{
std::string decodedStr;
std::string curr;
for (char ch : encodedStr)
{
curr += ch;
if (reverseCodes.find(curr) != reverseCodes.end())
{
decodedStr += reverseCodes[curr];
curr.clear();
}
}
return decodedStr;
}