Skip to content

Instantly share code, notes, and snippets.

@sunwayforever
Created January 25, 2019 08:26
Show Gist options
  • Save sunwayforever/2f6fcf8fec2ab34d8938fcf83d59b81a to your computer and use it in GitHub Desktop.
Save sunwayforever/2f6fcf8fec2ab34d8938fcf83d59b81a to your computer and use it in GitHub Desktop.
trie.rs
use std::collections::HashMap;
#[derive(Default)]
struct TrieNode {
is_leaf: bool,
children: HashMap<char, TrieNode>,
}
impl TrieNode {
fn add(&mut self, s: String) {
let mut root = self;
for c in s.chars() {
root = root.children.entry(c).or_default();
}
root.is_leaf = true;
}
fn query(&self, s: String) -> bool {
let mut root = self;
for c in s.chars() {
if !root.children.contains_key(&c) {
return false;
}
root = root.children.get(&c).unwrap();
}
root.is_leaf
}
}
fn main() {
let mut root = TrieNode::default();
root.add("hello".to_owned());
println!("{:?}", root.query("hello".to_owned()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment