题目
实现前缀树,支持插入单词、精确搜索和前缀搜索。输入只含小写英文字母;精确搜索还要求终点被标记为完整单词。
示例输入
Trie
insert apple
search apple
search app
startsWith app
insert app
search app示例输出
[null,null,true,false,true,null,true]思路
从根沿字符边前进,相同前缀共享同一路径。插入时补建缺失节点;单词终点用 end 标记,区分已有前缀与完整单词。
每一步都成立
当前节点表示已经处理的字符前缀;end 只在完整插入单词的终点为真。
看它一步步执行
用的是题目示例按平常的写法填:数组写 2 7 11 15 或 2, 7, 11, 15,矩阵每行一行,字符串不用加引号。也可以把力扣的示例整行粘贴进来,例如 nums = [2,7,11,15], target = 9。
核对结果(可选)
数组 / 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}
← → 单步 · 空格 播放
自己写一遍
只需实现下面的方法,输入输出由判题机处理。运行用下方的测试用例试一试;提交再用约 10 组隐藏用例检验。草稿自动保存在这个浏览器里。
还没有运行。写好代码后点“运行”。
ListNode、TreeNode、Node 已经定义好,可以直接使用;java.util 已默认导入。单组输入最多运行 4 秒,提交最多 6 秒。服务器同一时间只运行一份代码,人多时可能要排队几秒。