Trie,又称前缀树或字典树。该树的每个节点包含以下字段:
- 指向子节点的指针数组children。
- 布尔字段isEnd
前缀树的每一条root节点到isEnd为true的节点路径为一个字符串。
前缀树有两个基础的操作:插入字符串和查询前缀。
208. 实现 Trie (前缀树) 难度:中等
package com.linzhongkai.datastructure.tree;public class Trie {private Trie[] children;private boolean isEnd;public Trie() {children = new Trie[26]; //26个字母isEnd = false;}public void insert(String word) {Trie node = this;for (int i = 0; i < word.length(); i++) {int index = word.charAt(i)-'a';if (node.children[index] == null) {node.children[index] = new Trie(); //表示该位置有字母,仅由小写字母构成}node = node.children[index];}node.isEnd = true;}public Trie searchPrefix(String prefix) {Trie node = this;for (int i = 0; i < prefix.length(); i++) {int index = prefix.charAt(i) - 'a';if (node.children[index] == null) {return null;}node = node.children[index];}return node;}public boolean search(String word) {Trie node = searchPrefix(word);return node != null && node.isEnd;}public boolean startWith(String prefix) {return searchPrefix(prefix) != null;}}
211. 添加与搜索单词 - 数据结构设计
思路:还是前缀树的思路,但是添加了’.’的处理
``
