1.字典树:

为字典设计的数据结构,专门处理字符串。
假如通讯录里面有很多人,要想快速查找的话,二分树以及各类排序算法实际上都不合适。
因此采用字典树结构

2.字典树结构:

字典树的节点不止一个,对于英语来说,每个节点有26个指向下面节点的指针,我们可以不用保留节点本身的值。

  1. class Node{
  2. private char val;
  3. private Map<char, Node> next;
  4. }
  5. // 定义Node

但是对于进行遍历时,需要查看是否为单词,例如 pan / panda, 因此需要加入 isWord 判定在该节点时,是否为end。

  1. // 定义 Node
  2. class Node{
  3. private isWord;
  4. private Map<char, Node> next;
  5. public Node(Boolean isWord){
  6. this.isWord = isWord;
  7. }
  8. public Node(){
  9. this(null);
  10. }
  11. }

3.具体实现

  1. //实现字典树
  2. public class Trie{
  3. class Node{
  4. private isWord;
  5. private Map<char, Node> next;
  6. public Node(Boolean isWord){
  7. this.isWord = isWord;
  8. next = new TreeMap<>();
  9. }
  10. public Node(){
  11. this(null);
  12. }
  13. }
  14. private Node root;
  15. private int size;
  16. public Trie(){
  17. root = null;
  18. size = 0;
  19. }
  20. // 添加单词
  21. public void add(String word){
  22. if(word == null) return false;
  23. Node cur = root;
  24. for(int i = 0; i < word.length(); i++){
  25. char c = word.charAt(i);
  26. if(cur.next.get(c) == null){
  27. cur.next.put(c, new Node());
  28. }
  29. cur = cur.next.get(c);
  30. }
  31. if(!cur.isWord){
  32. cur.isWord = true;
  33. size++;
  34. }
  35. }
  36. // 查询单词
  37. public boolean has_word(String word){
  38. if(word == null) return false;
  39. Node cur = root;
  40. for(int i = 0; i < word.length(); i++){
  41. char c = word.charAt(i);
  42. if(cur.next.get(c) == null){
  43. return false;
  44. }
  45. cur = cur.next.get(c);
  46. }
  47. // 传入 panda 为单词,但是 Pan未传入,不能算作单词
  48. return cur.isWord;
  49. }
  50. }

4.优化:添加前缀查询

  1. public boolean isPrefix(String prefix){
  2. if(prefix == null) return false;
  3. Node cur = root;
  4. for(int i = 0; i <prefix.length(); i++){
  5. char c = prefix.charAt(i);
  6. if(cur.next.get(c) == null){
  7. return false;
  8. }
  9. cur = cur.next.get(c);
  10. }
  11. return true;
  12. }

5.相关问题:

leetcode 208
leetcode 211

6.相关优化:

将每个节点不再只是一个字符,而是可以保存一个单词。
压缩字典树 / 字串查询 / 模式匹配问题