208. Implement Trie (Prefix Tree) (Rust version)

/**
208. Implement Trie (Prefix Tree)
https://leetcode.com/problems/implement-trie-prefix-tree/description/

A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings.
There are various applications of this data structure, such as autocomplete and spellchecker.
Implement the Trie class:
Trie() Initializes the trie object.
void insert(String word) Inserts the string word into the trie.
boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.

Example 1:
Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]

Explanation
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // return True
trie.search("app");     // return False
trie.startsWith("app"); // return True
trie.insert("app");
trie.search("app");     // return True

Constraints:
1. 1 <= word.length, prefix.length <= 2000
2. word and prefix consist only of lowercase English letters.
3. At most 3 * 104 calls in total will be made to insert, search, and startsWith.
*/

const SIZE: usize = 26;

#[derive(Default)]//for use type's default value
pub struct Trie {
    nodes: [Option<Box<Trie>>; 26],
    is_word: bool,
}

/**
 * `&self` means the method takes an immutable reference.
 * If you need a mutable reference, change it to `&mut self` instead.
 */
impl Trie {
    pub fn new() -> Self {
        Default::default()
    }

    fn insert(&mut self, word: String) {
        let mut cur = self;
        //set (c as u8 - 'a' as u8) as index and return to 'index' which is index in nodes
        for index in word.chars().map(|c| (c as u8 - 'a' as u8) as usize) {
            cur = cur.nodes[index].get_or_insert(Box::new(Trie::new()));
        }
        cur.is_word = true;
    }

    fn search(&self, word: String) -> bool {
        let mut cur = self;
        for index in word.chars().map(|c| (c as u8 - 'a' as u8) as usize) {
            match cur.nodes[index].as_ref() {
                Some(node) => { cur = node }
                None => { return false; }
            }
        }
        cur.is_word
    }

    fn starts_with(&self, prefix: String) -> bool {
        let mut cur = self;
        for index in prefix.chars().map(|c| (c as u8 - 'a' as u8) as usize) {
            match cur.nodes[index].as_ref() {
                Some(node) => { cur = node }
                None => { return false; }
            }
        }
        true
    }
}

 

posted @ 2022-05-25 19:00  johnny_zhao  阅读(52)  评论(0编辑  收藏  举报