最長公共子序列(Longest Common Subsequenen, LCS)
1、概念
動態規劃(dynamic programming)是運籌學的一個分支,是求解決策過程(decision process)最優化的數學方法。
20世紀50年代初美國數學家R.E.Bellman等人在研究多階段決策過程(multistep decision process)的優化問題時,提出了著名的最優化原理(principle of optimality),把多階段過程轉化為一系列單階段問題,利用各階段之間的關系,逐個求解,創立了解決這類過程優化問題的新方法——動態規劃。
2、定義
一個序列A任意刪除若干個字符得到新序列B,則B叫做A的子序列。
兩個序列X和Y的公共子序列中,長度最長的那個,定義為X和Y的最長公共子序列。
例如X={A,B,C,B,D,A,B},Y={B,D,C,A,B,A}則它們的lcs是{B,C,B,A}和{B,D,A,B}。求出一個即可。
3、LCS的應用
相似度的比較: 計算生物學DNA對比(親子驗證),百度云盤找非法數據(島國片)。
圖形相似處理,媒體流的相似比較,百度知道,百度百科,WEB頁面中找非法言論。
4、特點及解決方法
特點:分析是從大到小,寫代碼是從小到大。
計算過程中會把結果都記錄下,最終結果在記錄中找到。
解決方法:
- 窮舉法(實際應用中不可取)
- 動態規劃法
5、算法分析
1. LCS的符號表示
字符串X,長度m,從1開始計數;
字符串Y,長度n,從1開始計數
LCS(X, Y)為字符串X和Y的最長公共子序列,其中的一個解為Z=<z1,z2,...zk>
注意:LCS(X,Y)其實為一個集合,Z為一個解
2. Xm = Yn
2.png
3.png
3. Xm != Yn
4.png
5.png
6.png
4. 代碼分析與編碼,規則:相同的取左上加1,不同取上和左中的最大值
1.png
6、代碼實現
import java.util.Stack;
/**
* 最長公共子序列
* author: bobo
* create time: 2018/12/27 1:54 PM
* email: jqbo84@163.com
*/
public class LCS {
/**
* 比較大小,返回大的
*
* @param a
* @param b
* @return
*/
public static int max(int a, int b) {
return a > b ? a : b;
}
/**
* 使用動態規劃的方式填入數據
*
* @param x
* @param y
* @return
*/
public static int[][] fillinLCS(String x, String y) {
char[] s1 = x.toCharArray();
char[] s2 = y.toCharArray();
int[][] array = new int[x.length() + 1][y.length() + 1];
//先把第一行和第一列填上零
for (int i = 0; i < array[0].length; i++) {
array[0][i] = 0;
}
for (int i = 0; i < array.length; i++) {
array[i][0] = 0;
}
//使用動態規劃的方式填入數據
for (int i = 1; i < array.length; i++) {
for (int j = 1; j < array[i].length; j++) {
if (s1[i - 1] == s2[j - 1]) {//如果相等,左上角加1填入
array[i][j] = array[i - 1][j - 1] + 1;
} else {//不等,取左和上的最大值
array[i][j] = max(array[i - 1][j], array[i][j - 1]);
}
}
}
return array;
}
/**
* 從后往前找到最長公共子序列結果
* @param x
* @param y
* @param left 表示當兩個值相等當情況,true:取左邊,false:取右邊
* @return
*/
public static String getLCS(String x, String y, boolean left) {
int[][] array = fillinLCS(x, y);
Stack stack = new Stack();
int i = x.length() - 1;
int j = y.length() - 1;
//從后往前找到結果
while (i >= 0 && j >= 0) {
if (x.charAt(i) == y.charAt(j)) {
stack.push(x.charAt(i));
i--;
j--;
} else {
//注意數組和String中的位置有一位差
if (array[i + 1][j + 1 - 1] > array[i + 1 - 1][j + 1]) {
if (left) j--;
else i--;
} else {
if (left) i--;
else j--;
}
}
}
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return sb.toString();
}
}
7、測試及結果
@Test
public void testLCS() {
int[][] array = LCS.fillinLCS("abcbdab", "bdcaba");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println("---------------------------");
String lcs = LCS.getLCS("abcbdab", "bdcaba", true);
System.out.println("lcs = " + lcs);
}
結果:
0 0 0 0 0 0 0
0 0 0 0 1 1 1
0 1 1 1 1 2 2
0 1 1 2 2 2 2
0 1 1 2 2 3 3
0 1 2 2 2 3 3
0 1 2 2 3 3 4
0 1 2 2 3 4 4
---------------------------
lcs = bcba