1. public static class Node2 {
    2. public int pass;
    3. public int end;
    4. public HashMap<Integer, Node2> nexts;
    5. public Node2() {
    6. pass = 0;
    7. end = 0;
    8. nexts = new HashMap<>();
    9. }
    10. }
    11. public static class Trie2 {
    12. private Node2 root;
    13. public Trie2() {
    14. root = new Node2();
    15. }
    16. public void insert(String word) {
    17. if (word == null) {
    18. return;
    19. }
    20. char[] chs = word.toCharArray();
    21. Node2 node = root;
    22. node.pass++;
    23. int index = 0;
    24. for (int i = 0; i < chs.length; i++) {
    25. index = (int) chs[i];
    26. if (!node.nexts.containsKey(index)) {
    27. node.nexts.put(index, new Node2());
    28. }
    29. node = node.nexts.get(index);
    30. node.pass++;
    31. }
    32. node.end++;
    33. }
    34. public void delete(String word) {
    35. if (search(word) != 0) {
    36. char[] chs = word.toCharArray();
    37. Node2 node = root;
    38. node.pass--;
    39. int index = 0;
    40. for (int i = 0; i < chs.length; i++) {
    41. index = (int) chs[i];
    42. if (--node.nexts.get(index).pass == 0) {
    43. node.nexts.remove(index);
    44. return;
    45. }
    46. node = node.nexts.get(index);
    47. }
    48. node.end--;
    49. }
    50. }
    51. // word这个单词之前加入过几次
    52. public int search(String word) {
    53. if (word == null) {
    54. return 0;
    55. }
    56. char[] chs = word.toCharArray();
    57. Node2 node = root;
    58. int index = 0;
    59. for (int i = 0; i < chs.length; i++) {
    60. index = (int) chs[i];
    61. if (!node.nexts.containsKey(index)) {
    62. return 0;
    63. }
    64. node = node.nexts.get(index);
    65. }
    66. return node.end;
    67. }
    68. // 所有加入的字符串中,有几个是以pre这个字符串作为前缀的
    69. public int prefixNumber(String pre) {
    70. if (pre == null) {
    71. return 0;
    72. }
    73. char[] chs = pre.toCharArray();
    74. Node2 node = root;
    75. int index = 0;
    76. for (int i = 0; i < chs.length; i++) {
    77. index = (int) chs[i];
    78. if (!node.nexts.containsKey(index)) {
    79. return 0;
    80. }
    81. node = node.nexts.get(index);
    82. }
    83. return node.pass;
    84. }
    85. }