在字典中查找单词,但从单词中删除了一个字母

时间:2015-05-09 22:16:19

标签: algorithm trie

我正在尝试理解以下算法,但我很难做一些事情:

首先输入是什么样的,即Aple或Ap_le和

其次这部分代码是做什么的?

“我们正在增加两种可能性:第一种         字符已被删除,加上第一个字符存在         countWords(vertex, word, missingLetters) k=firstCharacter(word) if isEmpty(word) return vertex.word else if notExists(edges[k]) and missingLetters=0 return 0 else if notExists(edges[k]) cutLeftmostCharacter(word) return countWords(vertex, word, missingLetters-1) Here we cut a character but we don't go lower in the tree else We are adding the two possibilities: the first character has been deleted plus the first character is present r=countWords(vertex, word, missingLetters-1) cutLeftmostCharacter(word) r=r+countWords(edges[k], word, missingLetters) return r

如果通过链接到顶点的所有edegs,第三个不应该是第二个吗?

来源: https://www.topcoder.com/community/data-science/data-science-tutorials/using-tries/

auto.assign=FALSE

1 个答案:

答案 0 :(得分:0)

首先:输入是树中的一个顶点(根)一个单词和一些丢失的字母。

例如:countWords(rootNode,“apple”,1)

树本质上是递归的,要理解这些算法,您应该将顶点视为在树的每个后续调用函数的起始位置。

现在我将用普通的psudo-er代码说出这个逻辑的每个部分是做什么的。

countWords(WhereYouAreAt, word, missingLetters)
    k = firstCharacter(word) # the first charactor is the next edge to traverse

    if(word = ""){Return(WhereYouAreAt.word)}

    else if (notExists(edges[k]) and missingLetters=0) {return 0} # Because you arn't at a word and and you can't make a word with the prefix that caused you to arrive at WhereYouAreAt.

    else if notExists(edges[k]){
         cutLeftmostCharacter(word)
         return countWords(vertex, word, missingLetters-1)
         #use one of the missing letters on the current letter. continue from WhereYouAre
    }

    else{
        cutLeftmostCharacter(word) #!!!
        r=countWords(vertex, word, missingLetters-1)
        r=r+countWords(edges[k], word, missingLetters) 
        return r
    }

其次是cutLeftmostCharacter(word)#!!!需要在您询问的行之前,该行计算节点下的单词数量WhereYouAreAt包含单词中剩余的字母减去n个missingLetters。第一行r =计数,如果你跳过单词中的第一个字母,r + =计数,如果你不跳过那个字母。

遗憾的是,由于输出可能会尝试并返回字符串和数字的总和,因此输出更糟糕......为了解决这个问题,我们需要将第一个if语句更改为

 if(word = ""){Return(vertex.words)}

而不是vertex.word ...

这样输出应该是字典中包含来自word的给定字母的有序子集的字数。

我希望这会有所帮助。

相关问题