2015-05-09 28 views
0

我想了解以下算法删除,但我有上几件事情很难:找到了一个词,一个字母是从字

首先是什么输入像即APLE或Ap_le和

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

“我们正在增加的两种可能性:第一 字符已被删除,加上第一个字符是目前 r=countWords(vertex, word, missingLetters-1)

第三不应该第二否则,如果经过连接到顶点的所有edegs?

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

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 
+0

只是一点提示:第二个ifelse只会最多再次调用countWords()。这是因为我们无法再匹配前缀(没有边界),但是我们仍然可以检查(通过调用countWords())如果再删除一个字母就会匹配。意思是,如果我们的单词匹配到目前为止,但最后还有一个额外的字符,那么我们认为它是匹配的(因为我们可以删除它)。 – synepis

+1

该代码需要输入如“aapple”或“appple”,并通过删除单个字母来查看是否可以将其变为单词。 –

回答

0

首先:输入是在树(根目录)的单词和多个丢失的信件的顶点。

例如:countWords(根节点,“苹果”,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(字)#!需要位于您询问的行的前面,其中包含节点WhereYouAreAt包含剩余字词中的字母减去n个missingLetters的字数。如果跳过单词中的第一个字母,则第一行r =计数,如果不跳过该字母,则r + =计数。

输出可惜还是被这样的事实变得更加严重,它可能会尝试,并返回一个字符串和数量的总和......解决这个问题,我们首先需要的if语句改为

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

而不是vertex.word ...

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

我希望这会有所帮助。

+0

非常感谢,非常有帮助! – user3154925

+0

只是一个问题,输入是否正确?我以为它应该是错过了一封信? – user3154925

+0

是的,它是一些缺少的字母,如果你想找到一个缺少字母的单词比你会有一个条件,如果(K ==“_”):总和所有边缘。 – kpie

相关问题