pub struct Trie { /* private fields */ }Expand description
Trie — har bir qirra bitta harf, ildizdan tugungacha bo’lgan yo’l — prefiks.
(root)
/ \
o k
| |
l i
/ \ |
m t t
| | |
[a] [i] [o] ← [ ] = so'z shu yerda tugaydi
|
[n]
→ "olma", "olti", "oltin", "kito"| Amal | Murakkablik | Izoh |
|---|---|---|
insert / contains | O(m) | m — so’z uzunligi, lug’at hajmiga bog’liq emas! |
starts_with | O(m) | prefiks bormi |
words_with_prefix | O(m + natija) | avtoto’ldirish |
Qayerda ishlatiladi: qidiruv qatoridagi avtoto’ldirish, telefondagi T9, imlo tekshirgich, IP marshrutlash jadvallari, so’z o’yinlari.
HashSet dan farqi: HashSet “bu so’z bormi?” ga javob beradi, Trie esa
prefiks bo’yicha ham qidira oladi va xotirada umumiy prefikslarni bir marta saqlaydi.
§Misol
use rust_algorithms::tree::Trie;
let mut t = Trie::new();
for so_z in ["olma", "olti", "oltin", "kitob"] {
t.insert(so_z);
}
assert!(t.contains("olma"));
assert!(!t.contains("ol")); // "ol" — so'z emas, faqat prefiks
assert!(t.starts_with("ol"));
let mut topilgan = t.words_with_prefix("olt");
topilgan.sort();
assert_eq!(topilgan, vec!["olti", "oltin"]);
assert_eq!(t.len(), 4);Implementations§
Source§impl Trie
impl Trie
Sourcepub fn starts_with(&self, prefix: &str) -> bool
pub fn starts_with(&self, prefix: &str) -> bool
Shu prefiks bilan boshlanadigan so’z bormi?
Sourcepub fn words_with_prefix(&self, prefix: &str) -> Vec<String>
pub fn words_with_prefix(&self, prefix: &str) -> Vec<String>
Prefiks bilan boshlanadigan barcha so’zlar (avtoto’ldirish).
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Trie
impl RefUnwindSafe for Trie
impl Send for Trie
impl Sync for Trie
impl Unpin for Trie
impl UnsafeUnpin for Trie
impl UnwindSafe for Trie
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more