-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.rs
94 lines (80 loc) · 2.23 KB
/
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
#![allow(dead_code)]
use std::{collections::HashMap, hash::Hash};
#[derive(Debug, Default)]
pub(crate) struct Trie<T: Hash + Eq> {
pub(crate) children: HashMap<T, Box<Trie<T>>>,
pub(crate) is_end: bool,
}
impl<T: Hash + Eq> Trie<T> {
pub fn new() -> Self {
Self {
children: HashMap::new(),
is_end: false,
}
}
pub fn insert(&mut self, seq: impl Iterator<Item = T>) {
let mut node = self;
for c in seq {
node = node.children.entry(c).or_insert_with(|| Trie::new().into());
}
node.is_end = true;
}
pub fn search(&self, seq: impl Iterator<Item = T>) -> bool {
let mut node = self;
for c in seq {
if let Some(next) = node.children.get(&c) {
node = next;
} else {
return false;
}
}
node.is_end
}
pub fn starts_with(&self, seq: impl Iterator<Item = T>) -> bool {
let mut node = self;
for c in seq {
if let Some(next) = node.children.get(&c) {
node = next;
} else {
return false;
}
}
true
}
}
#[cfg(test)]
mod generic_trie_test {
use super::*;
#[test]
fn string_case() {
let mut trie = Trie::new();
trie.insert("apple".chars());
assert!(trie.search("apple".chars()));
assert!(!trie.search("app".chars()));
assert!(trie.starts_with("apple".chars()));
assert!(trie.starts_with("app".chars()));
trie.insert("app".chars());
assert!(trie.search("app".chars()));
assert!(trie.starts_with("app".chars()));
trie.insert("appleTree".chars());
assert!(trie.search("appleTree".chars()));
assert!(!trie.search("appleT".chars()));
assert!(trie.starts_with("appleT".chars()));
}
#[test]
fn seq_case() {
let mut trie = Trie::new();
trie.insert([1, 2, 3].iter());
assert!(trie.search([1, 2, 3].iter()));
assert!(!trie.search([1, 2].iter()));
assert!(trie.starts_with([1, 2, 3].iter()));
assert!(trie.starts_with([1, 2].iter()));
trie.insert([1, 2].iter());
assert!(trie.search([1, 2].iter()));
assert!(trie.starts_with([1, 2].iter()));
trie.insert([1, 2, 3, 4, 5].iter());
assert!(trie.search([1, 2, 3, 4, 5].iter()));
assert!(!trie.search([1, 2, 3, 4].iter()));
assert!(trie.starts_with([1, 2, 3, 4].iter()));
}
}