Bug di sottostringa più lungo comune
-
23-12-2019 - |
Domanda
L'ho reso così lontano
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"))
.
Sfortunatamente stampa solo "D" e non "BCD" come previsto.Per me sembra che la linea "L2= LCS (XS, YSTR)" non sia eseguita perché se aggiungo la stampa di debug all'inizio stampa che la funzione non è stata chiamata argomenti di spirito "BCD" e "BCD",Ma sono sicuro che i valori vanno bene dopo l'altra dichiarazione. Apprezzerei qualsiasi aiuto.
Soluzione
La tua variabile xs
è globale
l1 = lcs(xstr, ys)
l2 = lcs(xs, ystr)
.
La prima riga corrompe il valore xs
utilizzato dalla seconda riga.
Fai tutte le tue variabili temporanee (x, y, xs, ys, l1, l2) locale.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow