Created
January 25, 2019 08:26
-
-
Save sunwayforever/2f6fcf8fec2ab34d8938fcf83d59b81a to your computer and use it in GitHub Desktop.
trie.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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