最常见的子串bug

时间:2014-02-27 15:27:07

标签: algorithm lua longest-substring

到目前为止,我已经做到了这一点

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语句开始之后,这些值是正常的。 我将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:3)

您的xs变量是全局的

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

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

相关问题