Advertisement
theultraman20

trie.rs

Aug 5th, 2024
389
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.14 KB | None | 0 0
  1. use crate::hash_map::HashMap;
  2.  
  3. pub struct Trie {
  4.     root: TrieNode,
  5. }
  6.  
  7. impl Trie {
  8.     pub fn new() -> Self {
  9.         Self { root: TrieNode::new() }
  10.     }
  11.  
  12.     pub fn insert(&mut self, slice: &str) {
  13.         self.root.insert(slice);
  14.     }
  15.  
  16.     pub fn search(&self, slice: &str) -> bool {
  17.         self.root.search(slice)
  18.     }
  19. }
  20.  
  21. //performance wise, this data structure seems kinda ret arded honestly
  22. struct TrieNode {
  23.     children: HashMap<char, TrieNode>,
  24.     is_tail: bool,
  25. }
  26.  
  27. impl TrieNode {
  28.     fn new() -> Self {
  29.         TrieNode { children: HashMap::new(), is_tail: false }
  30.     }
  31.  
  32.     fn insert(&mut self, slice: &str) {
  33.         let ch = slice.as_bytes()[0] as char;
  34.  
  35.         let node = match self.children.get_mut(ch) {
  36.             Some(node) => node,
  37.             None => self.children.insert(ch, TrieNode::new()),
  38.         };
  39.  
  40.         if slice.len() == 1 {
  41.             node.is_tail = true;
  42.         } else {
  43.             node.insert(&slice[1..]);
  44.         }
  45.     }
  46.  
  47.     fn search(&self, slice: &str) -> bool {
  48.         let ch = slice.as_bytes()[0] as char;
  49.  
  50.         match self.children.get(ch) {
  51.             Some(node) => {
  52.                 if slice.len() == 1 {
  53.                     return node.is_tail
  54.                 } else {
  55.                     node.search(&slice[1..])
  56.                 }
  57.             },
  58.             None => false,
  59.         }
  60.     }
  61. }
  62.  
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement