import java.util.*; public class Solution { //dp[i][j]表示字符串1前i个和字符串2前j个中最长公共子串,注意的说,我们子串连续 public static String LCS (String str1, String str2) { // write code here //1.建表 int n = str1.length(),m = str2.length(); String[][] dp = new String[n+1][m+1]; //虚拟节点设为空即可 for(int i=0;i<=n;i++){ for(int j=0;j<=m;j++){ dp[i][j] = ""; } } String longstr = ""; //2.填表 ,分为当前位置字符相同和当前位置字符不同 for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(str1.charAt(i-1)==str2.charAt(j-1)){ dp[i][j] = dp[i-1][j-1] +str1.charAt(i-1); longstr = dp[i][j].length() > longstr.length() ? dp[i][j] :longstr; }else{ //不相同时,就为空,子串需要连续, dp[i][j] = ""; } } } return longstr; } }