classSolution{ publicintlongestCommonSubsequence(String text1, String text2){ // DP solution, matrix to record the length int n = text1.length(); int m = text2.length(); // Extend one more row and column since we're comparing two different strings // that will need to calculate every position in the matrix. // Every position need its neighbors to calculate the length. int matrix[][] = newint[m + 1][n + 1]; // Set first row and first column to 0 for initialize which represent the empty string for (int i = 0; i <= n; i++) { matrix[0][i] = 0; } for (int i = 0; i <= m; i++) { matrix[i][0] = 0; } int maxLen = 0; // from left to right, top to bottom for (int col = 1; col <= n; col++) { for (int row = 1; row <= m; row++){ if (text1.charAt(col - 1) == text2.charAt(row - 1)) { matrix[row][col] = matrix[row - 1][col - 1] + 1; } else { matrix[row][col] = Math.max(matrix[row][col - 1], matrix[row - 1][col]); } maxLen = Math.max(maxLen, matrix[row][col]); } } return maxLen; } }