最长公共子串错误。

我到目前为止做了这个

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 语句的开头后这两个值都是正确的。 我将不胜感激任何帮助。

点赞
用户1847592
用户1847592

你的 xs 变量是全局的

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

第一行破坏了第二行使用的 xs 的值。

将所有临时变量 (x,y,xs,ys,l1,l2) 设为局部变量。

2014-02-27 15:54:53