参考链接

实现

  1. import java.util.HashMap;
  2. import java.util.Map;
  3. /**
  4. * 字典树, 以实现基本的增删查操作
  5. */
  6. public class Trie {
  7. /**
  8. * 根结点
  9. */
  10. private Node root;
  11. /**
  12. * 单词数量
  13. */
  14. private int size;
  15. public Trie() {
  16. root = new Node();
  17. }
  18. /**
  19. * 添加单词
  20. *
  21. * @param word 单词
  22. */
  23. public void add(String word) {
  24. Node p = root;
  25. for (char ch : word.toCharArray()) {
  26. if (p.next.get(ch) == null) {
  27. p.next.put(ch, new Node());
  28. }
  29. p = p.next.get(ch);
  30. }
  31. // 该节点上没有单词则加上单词
  32. // 防止相同单词重复添加
  33. if (!p.isWord) {
  34. p.isWord = true;
  35. ++size;
  36. }
  37. }
  38. /**
  39. * 查询单词
  40. *
  41. * @param word 单词
  42. * @return 是否存在于Trie中
  43. */
  44. public boolean contains(String word) {
  45. Node p = root;
  46. for (char ch : word.toCharArray()) {
  47. p = p.next.get(ch);
  48. if (p == null) {
  49. return false;
  50. }
  51. }
  52. return p.isWord;
  53. }
  54. /**
  55. * 删除一个单词
  56. *
  57. * @param word 单词
  58. * @return 是否删除成功
  59. */
  60. public boolean delete(String word) {
  61. Node p = root;
  62. for (char ch : word.toCharArray()) {
  63. p = p.next.get(ch);
  64. if (p == null) {
  65. return false;
  66. }
  67. }
  68. if (p.isWord) {
  69. --size;
  70. p.isWord = false;
  71. if (p.next.size() == 0) {
  72. p.next = null;
  73. p = null;
  74. }
  75. return true;
  76. } else {
  77. return false;
  78. }
  79. }
  80. }
  81. /**
  82. * 字符结点
  83. */
  84. class Node {
  85. /**
  86. * 当前结点是否为某个单词的结尾
  87. */
  88. public boolean isWord;
  89. /**
  90. * 用Map存储子结点
  91. */
  92. public Map<Character, Node> next;
  93. public Node() {
  94. next = new HashMap<>();
  95. }
  96. public Node(boolean isWord) {
  97. this.isWord = isWord;
  98. }
  99. }
  100. class Main {
  101. public static void main(String[] args) {
  102. Trie trie = new Trie();
  103. trie.add("hello");
  104. trie.add("app");
  105. trie.add("test");
  106. System.out.println(trie.contains("test"));
  107. System.out.println(trie.contains("tes"));
  108. System.out.println(trie.delete("test"));
  109. System.out.println(trie.contains("test"));
  110. }
  111. }