forked from TheAlgorithms/Rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autocomplete_using_trie.rs
124 lines (97 loc) · 2.76 KB
/
autocomplete_using_trie.rs
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*
It autocomplete by prefix using added words.
word List => ["apple", "orange", "oregano"]
prefix => "or"
matches => ["orange", "oregano"]
*/
use std::collections::HashMap;
const END: char = '#';
#[derive(Debug)]
struct Trie(HashMap<char, Box<Trie>>);
impl Trie {
fn new() -> Self {
Trie(HashMap::new())
}
fn insert(&mut self, text: String) {
let mut trie = self;
for c in text.chars().collect::<Vec<char>>() {
trie = trie.0.entry(c).or_insert_with(|| Box::new(Trie::new()));
}
trie.0.insert(END, Box::new(Trie::new()));
}
fn find(&self, prefix: String) -> Vec<String> {
let mut trie = self;
for c in prefix.chars().collect::<Vec<char>>() {
let char_trie = trie.0.get(&c);
if let Some(char_trie) = char_trie {
trie = char_trie;
} else {
return vec![];
}
}
Self::_elements(trie)
.iter()
.map(|s| prefix.clone() + s)
.collect()
}
fn _elements(map: &Trie) -> Vec<String> {
let mut results = vec![];
for (c, v) in map.0.iter() {
let mut sub_result = vec![];
if c == &END {
sub_result.push("".to_owned())
} else {
Self::_elements(v)
.iter()
.map(|s| sub_result.push(c.to_string() + s))
.collect()
}
results.extend(sub_result)
}
results
}
}
pub struct Autocomplete {
trie: Trie,
}
impl Autocomplete {
fn new() -> Self {
Self { trie: Trie::new() }
}
pub fn insert_words(&mut self, words: Vec<String>) {
for word in words {
self.trie.insert(word);
}
}
pub fn find_words(&self, prefix: String) -> Vec<String> {
self.trie.find(prefix)
}
}
impl Default for Autocomplete {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::Autocomplete;
#[test]
fn test_autocomplete() {
let words = vec![
"apple".to_owned(),
"orange".to_owned(),
"oregano".to_owned(),
];
let mut auto_complete = Autocomplete::new();
auto_complete.insert_words(words);
let prefix = "app".to_owned();
let mut auto_completed_words = auto_complete.find_words(prefix);
assert_eq!(auto_completed_words.sort(), vec!["apple".to_owned()].sort());
let prefix = "or".to_owned();
let mut auto_completed_words = auto_complete.find_words(prefix);
assert_eq!(
auto_completed_words.sort(),
vec!["orange".to_owned(), "oregano".to_owned()].sort()
);
}
}