Algorithm 最长公共子串错误
我已经做到了这一点Algorithm 最长公共子串错误,algorithm,lua,longest-substring,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
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语句开始之后值是正确的。
非常感谢您的帮助。您的
xs
变量是全局变量
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"))
l1 = lcs(xstr, ys)
l2 = lcs(xs, ystr)
第一行损坏第二行使用的xs
值。将所有临时变量(x、y、xs、ys、l1、l2)设为局部变量。您知道函数的时间复杂度是指数级的吗?是的,我知道。不管怎样,谢谢你告诉我。你知道怎么修吗?是的。我知道运行时间为O(mn)的算法
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"))