Skip to content

Instantly share code, notes, and snippets.

@jleeothon
Created October 5, 2014 15:03
Show Gist options
  • Save jleeothon/8396a43646648f251dec to your computer and use it in GitHub Desktop.
Save jleeothon/8396a43646648f251dec to your computer and use it in GitHub Desktop.
Ruby: lowest common ancestor (recursive)
def lcs s1, s2
if s1.empty? or s2.empty?
return ''
elsif s1[0] == s2[0]
return s1[0] + lcs(s1[1..-1], s2[1..-1])
end
left = lcs s1[1..-1], s2
right = lcs s1, s2[1..-1]
return left.size > right.size ? left : right
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment