【问题标题】:Longest common substring bug最长公共子串错误
【发布时间】:2014-03-31 03:26:37
【问题描述】:

到目前为止我已经做到了

function lcs(xstr, ystr)
        if xstr:len() == 0 or ystr:len() == 0 then
                return ""
        end
        x = xstr:sub(1,1)
        y = ystr:sub(1,1)
        xs = xstr:sub(2)
        ys = ystr:sub(2)
        if x == y then
                return x .. lcs(xs, ys)
        else
                l1 = lcs(xstr, ys)
                l2 = lcs(xs, ystr)
                if l1:len() > l2:len() then
                        return l1
                else
                        return l2
                end
        end
end

print(lcs("abcd", "bcd"))

不幸的是,它只打印“d”而不是“bcd”。对我来说,“l2 = lcs(xs, ystr)”这一行似乎没有被执行,因为如果我在开头添加调试打印,它会打印出该函数没有被称为机智参数“bcd”和“bcd”,但我确信在 else 语句开始后值没问题。 我将不胜感激。

【问题讨论】:

  • 你知道你的函数有指数时间复杂度吗?
  • 是的,我愿意。不管怎样,谢谢你告诉我。
  • 你知道怎么解决吗?
  • 是的。我知道算法的运行时间为 O(mn)

标签: algorithm lua longest-substring


【解决方案1】:

您的xs 变量是全局变量

l1 = lcs(xstr, ys)
l2 = lcs(xs, ystr)

第一行损坏了第二行使用的 xs 值。
将所有临时变量(x、y、xs、ys、l1、l2)设为本地变量。

【讨论】:

    猜你喜欢
    • 2014-04-14
    • 2016-06-03
    • 2010-11-28
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多