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
|
use std::collections::{HashMap, BinaryHeap};
use std::cmp::Reverse;
impl Solution {
pub fn huffman_encoding(freq: HashMap<char, i32>) -> HashMap<char, String> {
if freq.len() == 1 {
let mut ans = HashMap::new();
ans.insert(*freq.keys().next().unwrap(), "0".to_string());
return ans;
}
let mut heap = BinaryHeap::new();
for (ch, f) in freq {
heap.push(Reverse(Node::new(Some(ch), f)));
}
while heap.len() > 1 {
let Reverse(left) = heap.pop().unwrap();
let Reverse(right) = heap.pop().unwrap();
let merged = Node {
ch: None,
freq: left.freq + right.freq,
left: Some(Box::new(left)),
right: Some(Box::new(right)),
};
heap.push(Reverse(merged));
}
let Reverse(root) = heap.pop().unwrap();
let mut ans = HashMap::new();
Self::generate_codes(&root, String::new(), &mut ans);
ans
}
fn generate_codes(node: &Node, code: String, ans: &mut HashMap<char, String>) {
if node.left.is_none() && node.right.is_none() {
if let Some(ch) = node.ch {
ans.insert(ch, code);
}
return;
}
if let Some(ref left) = node.left {
Self::generate_codes(left, code.clone() + "0", ans);
}
if let Some(ref right) = node.right {
Self::generate_codes(right, code + "1", ans);
}
}
}
#[derive(Eq, PartialEq)]
struct Node {
ch: Option<char>,
freq: i32,
left: Option<Box<Node>>,
right: Option<Box<Node>>,
}
impl Node {
fn new(ch: Option<char>, freq: i32) -> Self {
Node {
ch,
freq,
left: None,
right: None,
}
}
}
impl Ord for Node {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.freq.cmp(&other.freq)
}
}
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
|