RosettaCodeData/Task/Longest-common-subsequence/Ruby/longest-common-subsequence-1.rb

15 lines
315 B
Ruby
Raw Permalink Normal View History

2013-04-10 21:29:02 -07:00
=begin
irb(main):001:0> lcs('thisisatest', 'testing123testing')
=> "tsitest"
=end
def lcs(xstr, ystr)
2015-02-20 00:35:01 -05:00
return "" if xstr.empty? || ystr.empty?
2013-04-10 21:29:02 -07:00
2015-02-20 00:35:01 -05:00
x, xs, y, ys = xstr[0..0], xstr[1..-1], ystr[0..0], ystr[1..-1]
if x == y
x + lcs(xs, ys)
else
[lcs(xstr, ys), lcs(xs, ystr)].max_by {|x| x.size}
end
2013-04-10 21:29:02 -07:00
end