我有一个前缀树来存储大量的单词。现在,如果我想找到所有带有公共前缀“a”的单词,我首先检索包含 a 的第一个节点,然后在第一个节点的子节点中以深度优先方式彻底搜索。虽然这个想法看起来很天真和简单,但如果具有公共前缀的单词的可能数量非常高(> 20K),它实际上是非常缓慢的。有没有其他方法可以有效地检索所有以公共前缀开头的单词?还是我应该采用其他数据结构?提前谢谢你。
EDIT1 基本上我通过访问每个节点并逐步添加字符来创建一个完整的单词。所有单词稍后都存储在向量容器中。是的,我有递归实现。
编辑2
vector<int> getNonEmptyEdgeIndices(Node* parent) {
vector<int> indices;
for(int i=0; i<EDGE; i++) {
if (parent->edges[i] != NULL) {
indices.push_back(i);
}
}
return indices;
}
vector<string> getSubsequentStrings(vector<string> wordsStartingWith, Node* node, string prefix) {
vector<int> indices = getNonEmptyEdgeIndices(node);
// push the word to the container if node is a leaf
if (indices.empty()) {
wordsStartingWith.push_back(prefix);
return wordsStartingWith;
}
// if frequency is set in node, push the word but still continue recursion
if (node->frequency != 0) {
wordsStartingWith.push_back(prefix);
}
// look all the children of the node
for(unsigned int i=0; i<indices.size(); i++) {
string newPrefix = prefix + getNodeChar(indices[i]);
Node* child = node->edges[indices[i]];
// recursively get the prefix for all children
wordsStartingWith = getSubsequentStrings(wordsStartingWith, child, newPrefix);
}
return wordsStartingWith;
}
vector<string> Trie::getWordsStartingWith(string prefix) {
vector<string> wordsStartingWith;
Node* lastNode = getLastNode(prefix);
if (lastNode != NULL) {
wordsStartingWith = getSubsequentStrings(wordsStartingWith, lastNode, prefix);
}
return wordsStartingWith;
}
编辑 3 已解决!!!我的实现实际上存在问题。我在递归调用中传递了这个巨大的向量字符串容器,这实际上是问题所在。谢谢大家的好意建议。