java - 实现 Trie 数据结构的问题
问题描述
我对 Trie 实现方面的嵌套类有疑问
我想知道在 Trie 类内部和 Trie 类外部定义 TrieNode 类有什么区别
如果我在 Trie 类之外实现 TrieNode 类,当我尝试使用 Insert 方法时,它会在 (Trie.java:14) 处保持 sayig NullPointException,
因此,当我在 Trie 类之外实现 TrieNode 类时,如果我想解决 Nullpointexception 错误,任何人都可以解释两种方式之间的区别以及解决方案是什么。
这是我的代码
public class Trie {
private final TrieNode root;
public Trie () {
root = new TrieNode();
}
public void insert (String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null) {
node = new TrieNode();
current.children.put(ch, node);
}
current = node;
}
//mark the current nodes endOfWord as true
current.isEnd = true;
}
public boolean search (String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (current.children.get(ch) == null) {
return false;
}
current = current.children.get(ch);
}
return current.isEnd;
}
public void delete (String word) {
delete(root, word, 0);
}
private boolean delete (TrieNode node, String word, int index) {
if (index == word.length()) {
if (!node.isEnd) {
return false;
}
node.isEnd = false;
return node.children.size() == 0;
}
if (node == null) {
return false;
}
node = node.children.get(word.charAt(index));
boolean shouldBeDeleted = delete(node, word, index + 1);
if (shouldBeDeleted) {
node.children.remove(word.charAt(index));
return node.children.size() == 0;
}
return false;
}
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("abcd");
// System.out.println(trie.search("abcd"));
}
}
TrieNode 类分离为 Trie 类
public class TrieNode {
boolean isEnd;
Map<Character, TrieNode> children;
public void TrieNode () {
this.isEnd = false;
this.children = new HashMap<>();
}
}
解决方案
推荐阅读
- uber-api - 如何访问身份验证范围
- bootstrap-4 - Bootstrap SASS - 覆盖主题颜色
- docker - Nginx 不会将 http 重定向到 https
- flutter - 如何在颤振中使用 AES-256 加密字符串,以便使用 openSSL 在 Web 上解密
- javascript - 使用 Firebase Cloud Functions 时未定义 httpsCallable
- authentication - WebSphere 9 ND 节点代理停止,应用程序仍在工作。如何/为什么?
- memgraphdb - 如何将 Memgraph 图导出为一系列 Cypher 语句,以便我可以使用它将数据导入另一个实例或 Neo4j?
- c++ - 是否存在在作用域结束时不会为类调用类析构函数的情况?
- c++ - IDA pro 了解反汇编细节
- sql - 哪个逻辑运算符将返回较小的数据集?