The longest common subsequence is a very basic algorithm, but recently used to take to learn, there are a lot of Java version of the Web, and indeed write is very good, thinking is very good, roughly divided into three kinds:
1. The thought based on recursion
2. The idea based on dynamic programming
3. Dynamic programming based on HashMap
Here I use Python to implement, the method is very simple, first look at the program:
#!usr/bin/env python
#encoding: Utf-8
'
__author__: Yishui Cold city
function: Compute the longest common subsequence between strings
'
def get_ LCS (string1, string2):
"
input: Two string outputs to be compared
: List of (subsequence length, subsequence) of descending output"
string1_list=list ( string1)
string2_list=list (string2)
lcs_list=[] for
i in range (len (string1_list)):
flag=0
lcs= '
for J in Range (I,len (string1_list)):
for K in range (flag, Len (string2_list)):
if string1_ LIST[J]==STRING2_LIST[K]:
lcs+=string1_list[j]
flag=k+1
lcs_list.append (Len (LCS), LCS
) Print Len (lcs_list) return
sorted (lcs_list, reverse=true)
if __name__ = ' __main__ ':
Lcs_list=get_lcs ("Abcdjio7890bhsdjknyewhbnvd", "Djio78347bvfdjbnknyew")
Print Lcs_list
The results are as follows:
[(One, ' Io77bbknyew '), (+, ' O77bbknyew '), (9, ' Ddjbknyew '), (9, ' Ddjbknyew '), (9, ' 77bbknyew '), (8, ' Jjbknyew '), (8 , ' Ddjknyew '), (8, ' Ddjknyew '), (8, ' Ddjknyew '), (8, ' 8bbknyew '), (7, ' Jjknyew '), (7, ' Bbknyew '), (7, ' Bbknyew '), (7,, ' BBK Nyew '), (7, ' Bbknyew '), (7, ' Bbknyew '), (5, ' Nnyew '), (5, ' Knyew '), (4, ' Bbnn '), (4, ' Bbnn '), (3, ' Yew '), (2, ' VD '), (2, ' the nn '), (2, ' ew '), (2, ' DD '), (1, ' W ')]
[finished in 0.5s]
The idea of the algorithm is also very simple, here is a simple: first, the string into a string list, starting with the first string as the benchmark to loop through the comparison, set the flag bit, in order to only compare the second string with the first string character after the same position of the string, rather than start over the comparison, The efficiency is ensured while the relative position of the elements in the resulting subsequence is the same as the relative position of the elements in the original string.