Trie,又称前缀树或字典树。该树的每个节点包含以下字段:

  1. 指向子节点的指针数组children。
  2. 布尔字段isEnd

前缀树的每一条root节点到isEnd为true的节点路径为一个字符串。
前缀树有两个基础的操作:插入字符串和查询前缀。

208. 实现 Trie (前缀树) 难度:中等

  1. package com.linzhongkai.datastructure.tree;
  2. public class Trie {
  3. private Trie[] children;
  4. private boolean isEnd;
  5. public Trie() {
  6. children = new Trie[26]; //26个字母
  7. isEnd = false;
  8. }
  9. public void insert(String word) {
  10. Trie node = this;
  11. for (int i = 0; i < word.length(); i++) {
  12. int index = word.charAt(i)-'a';
  13. if (node.children[index] == null) {
  14. node.children[index] = new Trie(); //表示该位置有字母,仅由小写字母构成
  15. }
  16. node = node.children[index];
  17. }
  18. node.isEnd = true;
  19. }
  20. public Trie searchPrefix(String prefix) {
  21. Trie node = this;
  22. for (int i = 0; i < prefix.length(); i++) {
  23. int index = prefix.charAt(i) - 'a';
  24. if (node.children[index] == null) {
  25. return null;
  26. }
  27. node = node.children[index];
  28. }
  29. return node;
  30. }
  31. public boolean search(String word) {
  32. Trie node = searchPrefix(word);
  33. return node != null && node.isEnd;
  34. }
  35. public boolean startWith(String prefix) {
  36. return searchPrefix(prefix) != null;
  37. }
  38. }

211. 添加与搜索单词 - 数据结构设计

思路:还是前缀树的思路,但是添加了’.’的处理
``