-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathimplement_magic_dictionary.rs
More file actions
80 lines (70 loc) · 2 KB
/
implement_magic_dictionary.rs
File metadata and controls
80 lines (70 loc) · 2 KB
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
use std::collections::HashMap;
struct TrieNode {
children: HashMap<char, Box<TrieNode>>,
leaf: bool,
}
struct MagicDictionary {
trie_root: Box<TrieNode>,
}
fn insert_trie(node: &mut Box<TrieNode>, word: &Vec<char>, pos: usize) {
if pos == word.len() {
node.leaf = true;
return;
}
if let Some(child_node) = node.children.get_mut(&word[pos]) {
insert_trie(child_node, word, pos + 1);
} else {
let mut child_node = Box::new(TrieNode {
children: HashMap::new(),
leaf: false,
});
insert_trie(&mut child_node, word, pos + 1);
node.children.insert(word[pos], child_node);
}
}
fn search_trie_with_one_change(
node: &TrieNode,
word: &Vec<char>,
pos: usize,
can_change: bool,
) -> bool {
if pos == word.len() {
return !can_change && node.leaf;
}
if let Some(child_node) = node.children.get(&word[pos]) {
if search_trie_with_one_change(child_node, word, pos + 1, can_change) {
return true;
}
}
if can_change {
for (char, child_node) in &node.children {
if *char != word[pos] {
if search_trie_with_one_change(child_node, word, pos + 1, false) {
return true;
}
}
}
}
false
}
impl MagicDictionary {
#[allow(dead_code)]
fn new() -> Self {
MagicDictionary {
trie_root: Box::new(TrieNode {
children: HashMap::new(),
leaf: false,
}),
}
}
#[allow(dead_code, clippy::needless_pass_by_value)]
fn build_dict(&mut self, dictionary: Vec<String>) {
for word in dictionary {
insert_trie(&mut self.trie_root, &word.chars().collect(), 0);
}
}
#[allow(dead_code, clippy::needless_pass_by_value)]
fn search(&self, search_word: String) -> bool {
search_trie_with_one_change(&self.trie_root, &search_word.chars().collect(), 0, true)
}
}