Created
November 13, 2022 17:15
-
-
Save dermesser/8be4da21c56f1568525f2f68dd732a39 to your computer and use it in GitHub Desktop.
Revisions
-
dermesser created this gist
Nov 13, 2022 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,38 @@ function longest_common_subsequence(x::Vector{T}, y::Vector{T})::Vector{T} where {T} m, n = length(x), length(y) C = zeros(Int, m+1, n+1) # Not necessary: for i = 1:m C[i,1] = 0 end for j = 1:n C[1,j] = 0 end for i = 1:m for j = 1:n if x[i] == y[j] C[i+1,j+1] = C[i, j] + 1 else C[i+1,j+1] = max(C[i, j+1], C[i+1, j]) end end end # Reconstruct sequence i, j = m, n k = C[m+1, n+1] seq = Vector{T}(undef, k) while k > 0 if C[i,j] + 1 == C[i+1,j+1] seq[k] = x[i] k -= 1 i -= 1 j -= 1 elseif C[i,j+1] == C[i+1,j+1] i -= 1 elseif C[i+1,j] == C[i+1,j+1] j -= 1 end end seq end