【问题标题】:Find a word in a dictionary but a single letter was deleted from the word在字典中查找一个单词,但该单词中删除了一个字母
【发布时间】: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”之类的输入,并查看是否可以通过删除单个字母将其变成单词。

标签: algorithm trie


【解决方案1】:

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

例如:countWords(rootNode,"apple",1)

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

现在我将用简单的伪代码说明这个逻辑的每个部分的作用。

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 个缺失的字母。如果您跳过单词中的第一个字母,则第一行 r= 计数,如果您不跳过该字母,则 r+= 计数。

不幸的是,输出仍然变得更糟,因为它可能会尝试返回一个字符串和一个数字的总和......为了解决这个问题,我们需要将第一个 if 语句更改为

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

而不是vertex.word ...

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

我希望这会有所帮助。

【讨论】:

  • 非常感谢,非常有帮助!
  • 只有一个问题,输入是否正确?我以为它应该少了一封信?
  • 是的,它是一些缺失的字母,如果你想找到缺失字母的单词,那么你将有一个条件 if(k == "_"): sum over all edges。
  • else if notExists(edges[k]) case:为什么要剪掉左边的字母? if (notExists(edges[k])),那表示k前面的字母不见了对吧?
猜你喜欢
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 2023-01-27
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 2016-12-21
  • 2021-06-28
相关资源
最近更新 更多