我正在尝试计算 Trie 中 prefixCount 的值,如下所示。
我很困惑为什么 count 的值没有返回为 3
为了以防万一,Tries 包含 [by,bye, byer,rat]。为什么 count 返回为 0,而不是 3。
public int prefixCount(String prefix)
{
int count = 0;
TrieNode node = searchPrefix(prefix);
if(node != null)
{
prefixCount(prefix, node, count);
}
return count;
}
public void prefixCount(String prefix, TrieNode node, int count)
{
if(node.isEnd())
{
count++;
}
for(int index = 0;index < 26;index++)
{
char value = (char) (index + 'a');
TrieNode next = node.get(value);
if(next != null)
{
prefixCount(prefix + value, next, count);
}
}
}
我在进行 DFS 操作时做错了什么吗?
谢谢!
最佳答案
我没有正确定义我的方法。适当的方法如下。
public int prefixCount(String prefix)
{
int count = 0;
TrieNode node = searchPrefix(prefix);
if(node.isEnd())
{
count++;
}
for(int index = 0;index < 26;index++)
{
char value = (char) (index + 'a');
TrieNode next = node.get(value);
if(next != null)
{
count += prefixCount(prefix + value);
}
}
return count;
}
谢谢!
关于java - 进行 DFS 时尝试中的原始值 (int),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48465112/