GRAPH

实现 Trie(前缀树)

中等#208时间 每个操作 O(L),L 为字符串长度空间 O(所有插入单词的字符总数)力扣原题 ↗

题目

实现前缀树,支持插入单词、精确搜索和前缀搜索。输入只含小写英文字母;精确搜索还要求终点被标记为完整单词。

示例输入Trie insert apple search apple search app startsWith app insert app search app
示例输出[null,null,true,false,true,null,true]

思路

从根沿字符边前进,相同前缀共享同一路径。插入时补建缺失节点;单词终点用 end 标记,区分已有前缀与完整单词。

每一步都成立

当前节点表示已经处理的字符前缀;end 只在完整插入单词的终点为真。

看它一步步执行

用的是题目示例
数组 / nums步骤 1
执行状态
这次的结果播放到最后查看

Solution.java参考解法 · 高亮的是正在执行的行
1class Trie {2    private final Trie[] children = new Trie[26];3    private boolean end;4    public Trie() { }5    public void insert(String word) {6        Trie node = this;7        for (int i = 0; i < word.length(); i++) {8            int index = word.charAt(i) - 'a';9            if (node.children[index] == null) node.children[index] = new Trie();10            node = node.children[index];11        }12        node.end = true;13    }14    public boolean search(String word) {15        Trie node = find(word);16        return node != null && node.end;17    }18    public boolean startsWith(String prefix) {19        return find(prefix) != null;20    }21    private Trie find(String word) {22        Trie node = this;23        for (int i = 0; i < word.length(); i++) {24            int index = word.charAt(i) - 'a';25            if (node.children[index] == null) return null;26            node = node.children[index];27        }28        return node;29    }30}
← → 单步 · 空格 播放
↑↓ 选择↵ 打开Pagefind 全文检索