1、最长公共子序列和最长公共子串的区别?
最长公共子序列:不要求子序列连续。
最长公共子串:要求子串一定连续。
2、最长公共子序列
最长公共子序列定义:两个或多个已知数列的子序列集合中最长的就是最长公共子序列。
比如数列A = “abcdef”和B = “adefcb”,那么两个数列的公共子序列集合有{”a","ab","abc","adef",等等},其中最长的就是adef,这就是最长公共子序列。
最长公共子序列LCS动态规划状态转移方程式
最长公共子序列动态规划解法
dp[i][j] -- 表示子串A[0...i](数组长度为n)和子串B[0...j](数组长度为m)的最长公共子序列
当A[i] == B[j]时,dp[i][j] = dp[i-1][j-1] + 1;
否则,dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
最优解为dp[n-1][m-1];
回溯输出最长公共子序列过程:
算法分析:
由于每次调用至少向上或向左(或向上向左同时)移动一步,故最多调用(m * n)次就会遇到i = 0或j = 0的情况,此时开始返回。返回时与递归调用时方向相反,步数相同,故算法时间复杂度为Θ(m * n)。
1 public class Solution { 2 3 public static void main(String[] args) { 4 String str1 = "12asdfa"; 5 String str2 = "we2rasdaswer"; 6 7 int result = longestCommonSubsequence(str1, str2); 8 System.out.println(result); 9 10 } 11 12 // LCS 13 public static int longestCommonSubsequence(String str1, String str2) { 14 int[][] matrix = new int[str1.length()+1][str2.length()+1]; 15 16 for(int i = 0; i < str1.length(); i++) { 17 matrix[i][0] = 0; 18 } 19 20 for(int j = 0; j <= str2.length(); j++) { 21 matrix[0][j] = 0; 22 } 23 24 for(int i = 1; i <= str1.length(); i++) { 25 for(int j = 1; j <= str2.length(); j++) { 26 if(str1.charAt(i-1) == str2.charAt(j-1)) { 27 matrix[i][j] = matrix[i-1][j-1] + 1; 28 } else { 29 matrix[i][j] = (matrix[i-1][j] >= matrix[i][j-1]?matrix[i-1][j]:matrix[i][j-1]); 30 } 31 } 32 } 33 34 return matrix[str1.length()][str2.length()]; 35 } 36 }
如何要得到重复的子序列是哪个?
3、最长公共子串
最长公共子串的动态规划的状态转移方程式
1 public class Solution { 2 public static void main(String[] args) { 3 4 String str1 = "abcdef"; 5 String str2 = "cde"; 6 7 int result = longestCommonSubstring(str1, str2); 8 System.out.println(result); 9 } 10 11 public static int longestCommonSubstring(String str1, String str2) { 12 int len1 = str1.length(); 13 int len2 = str2.length(); 14 int result = 0; 15 16 int[]][] c = new int[len1+1][len2+1]; 17 18 for(int i = 0; i <= len1; i++) { 19 for(int j = 0; j <= len2; j++) { 20 21 if(i == 0 || j == 0) { 22 c[i][j] = 0; 23 } else if(str1.charAt(i-1) == str2.charAt(j)) { 24 c[i][j] = c[i-1][j-1] + 1; 25 result = Math.max(result, c[i][j]); 26 } else { 27 c[i][j] = 0; 28 } 29 } 30 } 31 32 return result; 33 } 34 }