← 中文资源

简体中文版本

前缀树搜索与自动补全(Rust)

从词表构建前缀树,支持前缀搜索和按词频排序的自动补全。

阅读英文原文

实现说明

前缀树搜索与自动补全(Rust)的核心是函数 default、new、insert。 在这里做循环的是 for ch in word.chars() { node = node.children.entry(ch).or_default(); }。

使用要点

  • 值得导入的表面是 default;周围的辅助代码对片段是私有的。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 全部导入都来自标准库:std::collections。 文件在加载时定义 default、new、insert。

主要签名是 fn default() -> Self

核心语句

impl Default for TrieNode { fn default() -> Self { Self { children: HashMap::new(), is_word: false, freq: 0 } } }
fn new() -> Self { Self { root: Box::new(TrieNode::default()) } }
fn insert(&mut self, word: &str, freq: i32) {
    let mut node = &mut self.root;
    for ch in word.chars() { node = node.children.entry(ch).or_default(); }
    node.is_word = true; node.freq += freq;
}

代码示例

use std::collections::HashMap;

struct TrieNode { children: HashMap<char, Box<TrieNode>>, is_word: bool, freq: i32 }
impl Default for TrieNode { fn default() -> Self { Self { children: HashMap::new(), is_word: false, freq: 0 } } }

struct Trie { root: Box<TrieNode> }
impl Trie {
    fn new() -> Self { Self { root: Box::new(TrieNode::default()) } }
    fn insert(&mut self, word: &str, freq: i32) {
        let mut node = &mut self.root;
        for ch in word.chars() { node = node.children.entry(ch).or_default(); }
        node.is_word = true; node.freq += freq;
    }
}