这段代码实现了一个基于 Trie 树的字典树(Trie)数据结构,用于存储和检索字符串。其中包含以下几个方法. insert(String word): 向 Trie 树中插入一个单词。首先将单词转换为字符数组,然后遍历字符数组,逐个字符在 Trie 树中创建节点。每建一个节点,就将该节点的 pass 计数加一。最后将最后一个字符对应的节点的 end 计数加一。 search(String word): 在 Trie 树中查找一个单词。首先将单词转换为字符数组,然后遍历字符数组,逐个字符在 Trie 树中查找对应的节点。如果找不到某个字符对应的节点,说明该单词不存在于 Trie 树中,返回 0。否则继续查找下一个字符。最后返回最后一个字符对应的节点的 end 计数。 prefixNumber(String pre): 计算 Trie 树中以给定前缀开头的单词数量。首先将前缀转换为字符数组,然后遍历字符数组,逐个字符在 Trie 树中查找对应的节点。如果找不到某个字符对应的节点,说明没有以该前缀开头的单词,返回 0。否则继续查找下一个字符。最后返回最后一个字符对应的节点的 pass 计数。 delete(String word): 从 Trie 树中删除一个单词。首先检查该单词是否存在于 Trie 树中,如果存在,则按照插入的顺序逆序遍历字符数组,逐个字符在 Trie 树中删除对应的节点。每删除一个节点,就将该节点的 pass 计数减一。如果某个节点的 pass 计数变为 0,说明该节点不再被任何单词使用,可以将其删除。最后将最后一个字符对应的节点的 end 计数减一。
public class test5 {public static class Node1{public int pass;public int end;public Node1[] nexts;public Node1(){pass = 0;end = 0;nexts = new Node1[26];}}public static class Triel{private Node1 root;public Triel(){root = new Node1();}public void insert(String word){if(word == null){return;}char[] str = word.toCharArray();Node1 node = root;node.pass++;int path = 0;for (int i = 0; i < str.length; i++) {path = str[i] - 'a';if(node.nexts[path] == null){node.nexts[path] = new Node1();}node = node.nexts[path];node.pass++;}node.end++;}public int search(String word){if(word == null){return 0;}char[] chs = word.toCharArray();Node1 node = root;int index = 0;for (int i = 0; i < chs.length; i++) {index = chs[i] - 'a';if(node.nexts[index] == null){return 0;}node = node.nexts[index];}return node.end;}public int prefixNumber(String pre){if(pre == null){return 0;}char[] chs = pre.toCharArray();Node1 node = root;int index = 0;for (int i = 0; i < chs.length; i++) {index = chs[i] - 'a';if (node.nexts[index] == null) {return 0;}node = node.nexts[index];}return node.pass;}public void delete(String word){if(search(word) != 0){char[] chs = word.toCharArray();Node1 node = root;node.pass--;int index = 0;for (int i = 0; i < chs.length; i++) {index = chs[i] - 'a';if(--node.nexts[index].pass == 0){node.nexts[index] =null;return;}node = node.nexts[index];}node.end--;}}} }