Longest common subsequence: Difference between revisions

no edit summary
No edit summary
Line 1:
{{puzzle}}[[Category:Recursion]]
{{puzzle}}The '''longest common subsequence''' (or '''LCS''') of groups A and B is the longest group of elements from A and B that are common between the two groups and in the same order in each group. For example, the sequences "1234" and "1224533324" have an LCS of "1234":
'''<u>1234</u>'''
'''<u>12</u>'''245'''<u>3</u>'''332'''<u>4</u>'''
Line 194 ⟶ 195:
=={{header|Java}}==
===Recursion===
[[Category:Recursion]]This is not a particularly fast algorithm, but it gets the job done eventually. The speed is a result of many recursive function calls.
<java>public static String lcs(String a, String b){
if(a.length() == 0 || b.length() == 0){
Line 293 ⟶ 294:
=={{header|Python}}==
===Recursion===
[[Category:Recursion]]
This solution is similar to the Haskell's one. It is slow.
<python>def lcs(xstr, ystr):
longest = lambda xs, ys: (len(xs) > len(ys) and xs) or ys
 
def lcs(xstr, ystr):
"""
>>> lcs('thisisatest', 'testing123testing')
'tsitest'
"""
if not (xstr andor not ystr):
return ""
x, xs, y, ys = xstr[0], xstr[1:], ystr[0], ystr[1:]
Line 309 ⟶ 306:
return x + lcs(xs, ys)
else:
return longestmax(lcs(xstr, ys), lcs(xs, ystr), key=len)</python>
</python>
Test it:
<python>
Line 316 ⟶ 312:
import doctest; doctest.testmod()
</python>
 
===Dynamic Programming===
{{trans|Java}}
<python>def lcs(xstra, ystrb):
lengths = [[0 for j in range(len(b)+1)] for i in range(len(a)+1)]
# row 0 and column 0 are initialized to 0 already
for i in range(len(a)):
for j in range(len(b)):
if a[i] == b[j]:
lengths[i+1][j+1] = lengths[i][j] + 1
else:
lengths[i+1][j+1] = \
max(lengths[i+1][j], lengths[i][j+1])
# read the substring out from the matrix
result = ""
x, y = len(a), len(b)
while x != 0 and y != 0:
if lengths[x][y] == lengths[x-1][y]:
x -= 1
elif lengths[x][y] == lengths[x][y-1]:
y -= 1
else:
assert a[x-1] == b[y-1]
result = a[x-1] + result
x -= 1
y -= 1
return result</python>
Anonymous user