【发布时间】:2015-05-09 22:16:18
【问题描述】:
我正在尝试理解以下算法,但我在一些事情上遇到了困难:
首先输入是什么样的,即 Aple 或 Ap_le 和
其次,这部分代码是做什么的?
“我们添加了两种可能性:第一种
字符已被删除加上第一个字符存在
r=countWords(vertex, word, missingLetters-1)"
如果遍历所有链接到顶点的边,第三个不应该是第二个吗?
来源: 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
【问题讨论】:
-
一点提示:第二个 ifelse 最多只会再调用 1 次 countWords()。这是因为我们无法再匹配前缀(没有边),但我们仍然可以检查(通过调用 countWords())是否再删除一个字母会匹配。意思是,如果我们的单词到目前为止匹配,但我们最后有一个额外的字符,那么我们认为它是匹配的(因为我们可以删除它)。
-
该代码接受“aapple”或“appple”之类的输入,并查看是否可以通过删除单个字母将其变成单词。