最长公共子序列和最长公共子串

子串就是要连在一起的,而子序列就是满足这同时在1-n的母串中存在就好了。

比如abcdefg

子串有abc

子序列acdfg

动态规划
假设Z=<z1,z2,⋯,zk>是X与Y的LCS, 我们观察到
如果Xm=Yn,则Zk=Xm=Yn,有Zk−1是Xm−1与Yn−1的LCS;
如果Xm≠Yn,则Zk是Xm与Yn−1的LCS,或者是Xm−1与Yn的LCS。
因此,求解LCS的问题则变成递归求解的两个子问题。但是,上述的递归求解的办法中,重复的子问题多,效率低下。改进的办法——用空间换时间,用数组保存中间状态,方便后面的计算。这就是动态规划(DP)的核心思想了。

就是从整体看,然后将状态转移,可以得到问题转移的子问题就可以了。

DP求解LCS
用二维数组c[i][j]记录串x1x2⋯xi与y1y2⋯yj的LCS长度,则可得到状态转移方程

 1 public static int lcs(String str1, String str2) {
 2     int len1 = str1.length();
 3     int len2 = str2.length();
 4     int c[][] = new int[len1+1][len2+1];
 5     for (int i = 0; i <= len1; i++) {
 6         for( int j = 0; j <= len2; j++) {
 7             if(i == 0 || j == 0) {
 8                 c[i][j] = 0;
 9             } else if (str1.charAt(i-1) == str2.charAt(j-1)) {
10                 c[i][j] = c[i-1][j-1] + 1;
11             } else {
12                 c[i][j] = max(c[i - 1][j], c[i][j - 1]);
13             }
14         }
15     }
16     return c[len1][len2];
17 }

DP求解最长公共子串

前面提到了子串是一种特殊的子序列,因此同样可以用DP来解决。定义数组的存储含义对于后面推导转移方程显得尤为重要,糟糕的数组定义会导致异常繁杂的转移方程。考虑到子串的连续性,将二维数组c[i][j]用来记录具有这样特点的子串——结尾同时也为为串x1x2⋯xi与y1y2⋯yj的结尾——的长度。
得到转移方程:


最长公共子串的长度为 max(c[i,j]), i∈{1,⋯,m},j∈{1,⋯,n}。

 1 public static int lcs(String str1, String str2) {
 2     int len1 = str1.length();
 3     int len2 = str2.length();
 4     int result = 0;     //记录最长公共子串长度
 5     int c[][] = new int[len1+1][len2+1];
 6     for (int i = 0; i <= len1; i++) {
 7         for( int j = 0; j <= len2; j++) {
 8             if(i == 0 || j == 0) {
 9                 c[i][j] = 0;
10             } else if (str1.charAt(i-1) == str2.charAt(j-1)) {
11                 c[i][j] = c[i-1][j-1] + 1;
12                 result = max(c[i][j], result);
13             } else {
14                 c[i][j] = 0;
15             }
16         }
17     }
18     return result;
19 }
原文地址:https://www.cnblogs.com/blvt/p/7281679.html