参考这个问题,我问:How to find the longest word in a trie?
我在实现答案中给出的伪代码时遇到了麻烦。
findLongest(trie):
//first do a BFS and find the "last node"
queue <- []
queue.add(trie.root)
last <- nil
map <- empty map
while (not queue.empty()):
curr <- queue.pop()
for each son of curr:
queue.add(son)
map.put(son,curr) //marking curr as the parent of son
last <- curr
//in here, last indicate the leaf of the longest word
//Now, go up the trie and find the actual path/string
curr <- last
str = ""
while (curr != nil):
str = curr + str //we go from end to start
curr = map.get(curr)
return str
这就是我的方法
public static String longestWord (DTN d) {
Queue<DTN> holding = new ArrayQueue<DTN>();
holding.add(d);
DTN last = null;
Map<DTN,DTN> test = new ArrayMap<DTN,DTN>();
DTN curr;
while (!holding.isEmpty()) {
curr = holding.remove();
for (Map.Entry<String, DTN> e : curr.children.entries()) {
holding.add(curr.children.get(e));
test.put(curr.children.get(e), curr);
}
last = curr;
}
curr = last;
String str = "";
while (curr != null) {
str = curr + str;
curr = test.get(curr);
}
return str;
}
我在:
收到NullPointerException for (Map.Entry<String, DTN> e : curr.children.entries())
如何找到并修复方法的NullPointerException的原因,以便它返回trie中最长的单词?
答案 0 :(得分:1)
确保curr.children.entries()
不是空值。也许,如果该节点没有子节点,DTN
将返回空值。这会导致您的NullPointerException
。
在开始迭代之前尝试快速检查。
if(curr.children.entries() != null)
{
//It's safe, so procede with going deeper into the trie.
}
答案 1 :(得分:1)
除了@ Clark的答案之外,请确保在解除引用之前curr.children不为空。