1. // pass end nexts,没有节点就新建,有就通过pass+1,结尾end+1。
    2. public static class Node1 {
    3. public int pass; // 通过多少次
    4. public int end; // 节点是否是结尾
    5. public Node1[] nexts; // 当多了可以使用 HashMap<Char,Node> nexts;TreeMap<Char,Node> nexts;
    6. // char tmp = 'b' (tmp - 'a')
    7. public Node1() {
    8. pass = 0;
    9. end = 0;
    10. // 0 a
    11. // 1 b
    12. // 2 c
    13. // .. ..
    14. // 25 z
    15. // nexts[i] == null i方向的路不存在
    16. // nexts[i] != null i方向的路存在
    17. nexts = new Node1[26];
    18. }
    19. }
    20. public static class Trie1 {
    21. private Node1 root;
    22. public Trie1() {
    23. root = new Node1();
    24. }
    25. public void insert(String word) {
    26. if (word == null) {
    27. return;
    28. }
    29. char[] str = word.toCharArray();
    30. Node1 node = root;
    31. node.pass++;
    32. int path = 0;
    33. for (int i = 0; i < str.length; i++) { // 从左往右遍历字符
    34. path = str[i] - 'a'; // 由字符,对应成走向哪条路
    35. if (node.nexts[path] == null) {
    36. node.nexts[path] = new Node1();
    37. }
    38. node = node.nexts[path];
    39. node.pass++;
    40. }
    41. node.end++;
    42. }
    43. public void delete(String word) {
    44. if (search(word) != 0) {
    45. char[] chs = word.toCharArray();
    46. Node1 node = root;
    47. node.pass--;
    48. int path = 0;
    49. for (int i = 0; i < chs.length; i++) {
    50. path = chs[i] - 'a';
    51. if (--node.nexts[path].pass == 0) {
    52. node.nexts[path] = null;
    53. return;
    54. }
    55. node = node.nexts[path];
    56. }
    57. node.end--;
    58. }
    59. }
    60. // word这个单词之前加入过几次
    61. public int search(String word) {
    62. if (word == null) {
    63. return 0;
    64. }
    65. char[] chs = word.toCharArray();
    66. Node1 node = root;
    67. int index = 0;
    68. for (int i = 0; i < chs.length; i++) {
    69. index = chs[i] - 'a';
    70. if (node.nexts[index] == null) {
    71. return 0;
    72. }
    73. node = node.nexts[index];
    74. }
    75. return node.end;
    76. }
    77. // 所有加入的字符串中,有几个是以pre这个字符串作为前缀的
    78. public int prefixNumber(String pre) {
    79. if (pre == null) {
    80. return 0;
    81. }
    82. char[] chs = pre.toCharArray();
    83. Node1 node = root;
    84. int index = 0;
    85. for (int i = 0; i < chs.length; i++) {
    86. index = chs[i] - 'a';
    87. if (node.nexts[index] == null) {
    88. return 0;
    89. }
    90. node = node.nexts[index];
    91. }
    92. return node.pass;
    93. }
    94. }