java - 计算 Trie 中的单词数

标签 java trie

 int count=0;
     public  int countwords(TrieNode root){

        if (root.isTerminating==true)
            count++;

        for (int i=0;i<26;i++){
            if (root.children[i]!=null)
        countwords(root.children[i]);
        }

        return count;
    }

这个函数用于计算 trie 中的单词数,它给了我错误的答案,这里出了什么问题?我使用 isTerminate 来区分单词和另一个单词。

最佳答案

public int countwords(TrieNode root) {
   // variable localized because it is a recursive call
   // also because we add to this variable in the loop
   int count = 0;

   // if condition simplified
   if (root.isTerminating)
       count++;

   for (int i = 0; i < 26; i++) {
       if (root.children[i] != null)
           // you need to save the result of the recursive call
           count += countwords(root.children[i]);
    }
    return count;
}

关于java - 计算 Trie 中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61447716/

相关文章:

java - 是否可以以编程方式解析特定 IP 地址以负载平衡域名?

java - 性能静态初始化

c++ - 插入到 Trie 中,NULL 指针

嵌套字典的Python完整排序

java - 使用注释 @SuppressWarnings 忽略 Checkstyle 警告

java - 验证 Java 中调用的 Ibatis 过程

java - jps命令仅列出jps,但仍提供HDFS服务

c++ - 正确退出递归?

algorithm - 以最高分数解决拼字游戏

python - Python 中的 Trie(前缀树)