【问题标题】:Can't figure out this algorithm (recursive) on Trie operation在 Trie 操作中无法弄清楚这个算法(递归)
【发布时间】:2012-05-25 05:04:47
【问题描述】:

有人可以帮我理解以下 pheudocode 吗?

countWords(vertex, word, missingLetters)  
    k=firstCharacter(word)  
    if isEmpty(word)  
        return vertex.words  
    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    

我们的想法是使用Trie,我们试图找出一个单词在我们的字典中出现的次数,但我们可能缺少字母。
我迷失在else 部分。我不明白其中的逻辑。
例如,如果我们单词的第一个字符是匹配的,我们会点击最后一个 else,然后在同一级别上递归 countWords,但使用 missingLetters-1,但这不是一个相同的循环吗? IE。它会再次比较同一级别的第一个字母等等?
有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: algorithm data-structures dictionary computer-science trie


    【解决方案1】:

    即使最后几行的顺序按照 antti.huima 的建议颠倒了,我还是觉得有些不对劲。

    如果我理解正确,如果你有PizzaLizza 也应该在missingLetters==1 的情况下计算,对吧?但是,如果 Lizza 不在您输入的 trie 中

    else if notExists(edges['l'])  
            cutLeftmostCharacter(word) # 'izza' left  
            return countWords(vertex, 'izza', 0) #vertex is 'P' I guess
    

    然后你输入

    else if notExists(edges['i']) and missingLetters=0
    

    哪个返回 0?

    鉴于您已经尝试过,建议您查看Levehnstein Distance

    【讨论】:

      【解决方案2】:

      算法有问题。我怀疑由于某种原因,对 cutLeftMostCharacter 的最后一次调用已与前一行交换了。如果代码会读取

         cutLeftmostCharacter(word)  
         r=countWords(vertex, word, missingLetters-1)  
         r=r+countWords(edges[k], word, missingLetters)  
      

      这样会更有意义。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-03
        • 1970-01-01
        • 1970-01-01
        • 2010-10-03
        • 1970-01-01
        • 2016-12-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多