【问题标题】:How to properly check if a prefix of a word exists in a trie?如何正确检查trie中是否存在单词的前缀?
【发布时间】:2018-02-18 02:03:19
【问题描述】:

目前我的 Trie 类的“searchPrefix”函数定义如下:

public Boolean searchPrefix(String word) {
    TrieNode temp = this.root;
    for(int i = 0; i < word.length(); i++){
        if(temp.children.get(word.charAt(i)) == null) return false;
        else temp = temp.children.get(word.charAt(i));
    }
    return (temp.children.isEmpty()) ? false : true;
}

当输入字符串是存在于 trie 对象内部的单词的前缀时,该函数应该返回“true”。这里是 TrieNode 类供参考:

class TrieNode {
   Character c;
   Boolean isWord = false;
   HashMap<Character, TrieNode> children = new HashMap<>();

   public TrieNode() {}
   public TrieNode(Character c) {
    this.c = c;
   }
}

根据这个在线判断,我错误地确定了给定的输入字符串是否是前缀。任何人都可以阐明为什么这是一种不正确的方法吗?我的想法是,当我们到达作为输入字符串末尾的节点时,如果该节点有子节点,那么它就是其他单词的前缀,所以我们返回 true。然而这显然是不正确的。

【问题讨论】:

  • 空字符串呢?它是否被视为有效前缀?
  • 也缺少指向this online judge 的链接
  • @Devstr 在线评委是firecode.io。另外,由于在线法官的描述含糊不清,我不确定空字符串是否是前缀,但是似乎没有放置检查器“if(word.length()
  • 在下面查看我的答案

标签: java trie


【解决方案1】:

我认为您没有处理前缀是 trie 中的终端词的情况。

例如,假设在 trie 中只有一个词 hello。 您的实现将为 searchPrefix("hello") 返回 false。

要修复它,您还需要检查 isWord 标志:

public Boolean searchPrefix(String word) {
    TrieNode temp = this.root;
    for (int i = 0; i < word.length(); i++){
        TrieNode next = temp.children.get(word.charAt(i));
        if (next == null) {
            return false;
        }
        temp = next;
    }
    return !temp.children.isEmpty() || temp.isWord;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-30
    • 2013-05-24
    • 2015-01-04
    • 1970-01-01
    • 2013-03-27
    • 2017-12-11
    • 2011-05-28
    • 1970-01-01
    相关资源
    最近更新 更多