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) { // write code here if (str1 == null || str1.length() < 1 || str2 == null || str2.length() < 2) { return ""; } char[] arr1 = str1.toCharArray(); char[] arr2 = str2.toCharArray(); int n = arr1.length; int m = arr2.length; int[][] dp = new int[n + 1][m + 1]; int max = -1; int index = -1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { if (arr1[i - 1] == arr2[j - 1]) { dp[i][j] = dp[i - 1][j - 1] + 1; } if (dp[i][j] > max) { max = dp[i][j]; index = i - 1; } } } if (index > -1) { return str1.substring(index + 1 - max, index + 1); } return ""; } }