1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { char[] s1, s2; int[][] cache;
public int longestCommonSubsequence(String text1, String text2) { s1 = text1.toCharArray(); s2 = text2.toCharArray(); int n = s1.length, m = s2.length; cache = new int[n][m]; for (int i = 0; i < n; ++i) Arrays.fill(cache[i], -1); return dfs(n - 1, m - 1); }
private int dfs(int i, int j) { if (i < 0 || j < 0) return 0; if (cache[i][j] != -1) return cache[i][j]; if (s1[i] == s2[j]) return cache[i][j] = dfs(i - 1, j - 1) + 1; else return cache[i][j] = Math.max(dfs(i - 1, j), dfs(i, j - 1)); } }
|