二刷
import java.util.*; public class Solution { /** * longest common substring * @param str1 string字符串 the string * @param str2 string字符串 the string * @return string字符串 */ public String LCS (String str1, String str2) { int len1 = str1.length(); int len2 = str2.length(); int[][] dp = new int[len1+1][len2+1]; int maxindex = 0; int max = 0; for(int i=1;i<=len1;i++){ for(int j=1;j<=len2;j++){ if(str1.charAt(i-1) == str2.charAt(j-1)) { dp[i][j] = dp[i-1][j-1]+1; if(dp[i][j] > max){ max = dp[i][j]; maxindex = i-1; } } else dp[i][j] = 0; } } String res_s = str1.substring(maxindex-max+1,maxindex+1); return res_s; } }
动态规划
建立一个二维数组
首先初始化第一行和第一列
接下来 状态转移方程
dp[i][j] = dp[i-1][j-1] +1;
import java.util.*; public class Solution { /** * longest common substring * @param str1 string字符串 the string * @param str2 string字符串 the string * @return string字符串 */ public String LCS (String str1, String str2) { int maxLenth = 0;//记录最长公共子串的长度 int maxLastIndex = 0; int[][] dp = new int[str1.length()][str2.length()]; int i,j; // 初始化 for(i=0,j=0;i<str1.length();i++){ if(str1.charAt(i) == str2.charAt(j)){ dp[i][j] = 1; } else{dp[i][j] = 0;} } for(i=0,j=0;j<str2.length();j++){ if(str1.charAt(i) == str2.charAt(j)){ dp[i][j] = 1; } else{dp[i][j] = 0;} } // 更新 for(i=1;i<str1.length();i++){ for(j=1;j<str2.length();j++){ if(str1.charAt(i) == str2.charAt(j)){ dp[i][j] = dp[i-1][j-1] +1; if(dp[i][j] > maxLenth){ maxLenth = dp[i][j]; maxLastIndex = i; } }else{ dp[i][j] = 0; } } } return str1.substring(maxLastIndex + 1 - maxLenth, maxLastIndex+1); } }
2.最长公共子序列 待续。。。