首先要做的事情。您实际上不需要在节点类中存储字符属性,因为它已经隐式存储在其父节点的 children 属性中。
所以你的 Node 类实际上可以是:
class Node {
HashMap<Character, Node> children = new HashMap<>();
boolean isCompleteWord;
public Node(){
isCompleteWord = false;
}
}
此外,与所有有根树一样,您的 Trie 将需要一个根。在将任何单词存储到 Trie 之前,您需要一个 root。
root = new Node();
根节点代表空字符串,所以如果你需要存储它,你必须检查root的isCompleteWord属性。
然后,要插入一个单词,比如 myWord,您需要从根开始,并应用以下规则:
- 考虑第一个字母 myWord[0],比如'c'。您需要区分两种情况,root是否包含键'c'。如果它不包含该单词,则需要在 Trie 中创建一个新节点。否则,您只需要继续沿着树枝“走”。
- 到达最后一个字母后,您只需将属性isCompleteWord 设置为true。这是addWord 的一个可能的(完全未经测试的)实现,它在 Trie 中添加一个单词,如果它已经存在则返回 true,否则返回 false。
public bool addWord(Node node, String word, int idx){
if (idx == word.length() -1){
// we're checking the last letter
bool result = node.isCompleteWord;
node.isCompleteWord = true;
return result;
} else {
if (!node.children.containsKey(word.charAt(idx)){
// no child with this letter, create one
child = new Node()
node.children.put(word.charAt(idx), child);
}
return addWord(node.children(word.charAt(idx)), word, idx+1);
}
}
要在 Trie 中添加一个单词,比如myWord,您只需按如下方式调用它:
addWord(root, myWord, 0);
一个检查单词是否存储在 trie 中的函数与添加单词的函数非常相似。
public bool containsWord(Node node, String word, int idx){
if (idx == word.length() -1){
return node.isCompleteWord;
} else {
if (!node.children.containsKey(word.charAt(idx)){
// no child with this letter, the word is not in the trie
return false;
} else {
return containsWord(node.children(word.charAt(idx)), word, idx+1);
}
}
}