【问题标题】:Adapting pseudocode to java implementation for finding the longest word in a trie将伪代码改编为 java 实现以在 trie 中查找最长的单词
【发布时间】:2012-11-04 03:38:06
【问题描述】:

参考我问的这个问题: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 中最长的单词?

【问题讨论】:

    标签: java string algorithm trie


    【解决方案1】:

    确保curr.children.entries() 不是空值。如果该节点没有子节点,DTN 可能会返回一个空值。这会导致您的NullPointerException。

    在开始迭代之前尝试快速检查。

    if(curr.children.entries() != null)
    {
        //It's safe, so procede with going deeper into the trie.
    }
    

    【讨论】:

      【解决方案2】:

      除了@Clark 的回答,在取消引用之前确保 curr.children 不为空。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-24
        相关资源
        最近更新 更多