Rust_leetcode 208. 实现 Trie (前缀树)

字典树用于字符串处理
代码实现
#![allow(unused)]

use std::collections::HashMap;
use std::cell::RefCell;
use std::rc::Rc;


// 节点定义
struct Node {
    is_word: bool,
    next: HashMap<char, Rc<RefCell<Node>>>,
}

impl Node {
    pub fn new_with_is_word(is_word: bool) -> Self {
        return Self {
            is_word,
            next: HashMap::new(),
        };
    }
    pub fn new() -> Self {
        return Self {
            is_word: false,
            next: HashMap::new(),
        };
    }
}

// 字典树
struct Trie {
    root: Rc<RefCell<Node>>,
    size: usize,
}

impl Trie {
    pub fn new() -> Self {
        return Trie {
            root: Rc::new(RefCell::new(Node::new())),
            size: 0,
        };
    }

    pub fn get_size(&self) -> usize {
        return self.size;
    }

    // 添加单词
    pub fn insert(&mut self, word: String) {
        let mut tmp = self.root.clone();
        // 遍历单词
        for c in word.chars() {
            let n = tmp.borrow().next.get(&c).cloned();
            if let Some(no) = n {
                tmp = no.clone();
            } else {
                let t = Rc::new(RefCell::new(Node::new()));
                tmp.borrow_mut().next.insert(c, t.clone());
                tmp = t.clone()
            };
        }
        if tmp.borrow().is_word == false {
            tmp.borrow_mut().is_word = true;
            self.size += 1;
        }
    }

    // 包含
    pub fn search(&self, word: String) -> bool {
        let mut tmp = self.root.clone();

        for c in word.chars() {
            let n = tmp.borrow().next.get(&c).cloned();
            if let Some(no) = n {
                tmp = no.clone();
            } else {
                return false;
            };
        }
        if tmp.borrow().is_word == true {
            return true;
        }
        false
    }

    pub fn starts_with(&self, word: String) -> bool {
        let mut tmp = self.root.clone();

        for c in word.chars() {
            let n = tmp.borrow().next.get(&c).cloned();
            if let Some(no) = n {
                tmp = no.clone();
            } else {
                return false;
            };
        }
        return true;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let mut trie = Trie::new();
        trie.insert("pan".to_string());
        trie.insert("panda".to_string());
        assert_eq!(trie.search("pan".to_string()), true);
        assert_eq!(trie.search("pa".to_string()), false);
        assert_eq!(trie.starts_with("pand".to_string()), true);
    }
}
结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值