LCS问题陈述:给定两个序列,找出两个序列中存在的最长子序列的长度。子序列是以相同的相对顺序出现,但不一定是连续的序列。例如,“ abc”,“ abg”,“ bdf”,“ aeg”,“ acefg”等是“ abcdefg”的子序列。因此,长度为n的字符串具有2 ^ n个不同的可能子序列。
这是一个经典的计算机科学问题,是diff(文件比较程序,输出两个文件之间的差异)的基础,并已在生物信息学中得到应用。
例子:
输入序列“ ABCDGH”和“ AEDFHR”的LCS为长度3的“ ADH”。
输入序列“ AGGTAB”和“ GXTXAYB”的LCS是长度为4的“ GTAB”。
令输入序列分别为长度[m]和[n]的X [0..m-1]和Y [0..n-1]。并令L(X [0..m-1],Y [0..n-1])为两个序列X和Y的LCS的长度。以下是L(X [0 … m-1],Y [0..n-1])。
如果两个序列的最后一个字符匹配(或X [m-1] == Y [n-1]),则
L(X [0..m-1],Y [0..n-1])= 1 + L(X [0..m-2],Y [0..n-2])
如果两个序列的最后一个字符都不匹配(或X [m-1]!= Y [n-1]),则
L(X [0..m-1],Y [0..n-1])= MAX(L(X [0..m-2],Y [0..n-1]),L( X [0..m-1],Y [0..n-2])
/* A Naive recursive implementation of LCS problem in java*/
public class LongestCommonSubsequence {
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs(char[] X, char[] Y, int m, int n)
{
if (m == 0 || n == 0)
return 0;
if (X[m - 1] == Y[n - 1])
return 1 + lcs(X, Y, m - 1, n - 1);
else
return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n));
}
/* Utility function to get max of 2 integers */
int max(int a, int b)
{
return (a > b) ? a : b;
}
public static void main(String[] args)
{
LongestCommonSubsequence lcs = new LongestCommonSubsequence();
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
char[] X = s1.toCharArray();
char[] Y = s2.toCharArray();
int m = X.length;
int n = Y.length;
System.out.println("Length of LCS is"
+ " " + lcs.lcs(X, Y, m, n));
}
}
// This Code is Contributed by Saket Kumar
Length of LCS is 4
以下是LCS问题的列表实现。
/* Dynamic Programming Java implementation of LCS problem */
public class LongestCommonSubsequence {
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs(char[] X, char[] Y, int m, int n)
{
int L[][] = new int[m + 1][n + 1];
/* Following steps build L[m+1][n+1] in bottom up fashion. Note
that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X[i - 1] == Y[j - 1])
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = max(L[i - 1][j], L[i][j - 1]);
}
}
return L[m][n];
}
/* Utility function to get max of 2 integers */
int max(int a, int b)
{
return (a > b) ? a : b;
}
public static void main(String[] args)
{
LongestCommonSubsequence lcs = new LongestCommonSubsequence();
String s1 = "AGGTAB";
String s2 = "GXTXAYB";
char[] X = s1.toCharArray();
char[] Y = s2.toCharArray();
int m = X.length;
int n = Y.length;
System.out.println("Length of LCS is"
+ " " + lcs.lcs(X, Y, m, n));
}
}
// This Code is Contributed by Saket Kumar
Length of LCS is 4
请参考有关动态编程的完整文章。设置4(最长公共子序列)以获取更多详细信息!