|
|
|
@ -66,6 +66,41 @@ public class LongestCommonSubsequence {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static class Recursion1 {
|
|
|
|
|
public static int longestCommonSubsequence(String s1, String s2) {
|
|
|
|
|
if (s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0) {
|
|
|
|
|
return 0;
|
|
|
|
|
}
|
|
|
|
|
char[] c1 = s1.toCharArray();
|
|
|
|
|
char[] c2 = s2.toCharArray();
|
|
|
|
|
return process(c1, c2, c1.length - 1, c2.length - 1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static int process(char[] c1, char[] c2, int i, int j) {
|
|
|
|
|
if (i == 0 && j == 0) {
|
|
|
|
|
return c1[i] == c2[j] ? 1: 0;
|
|
|
|
|
} else if (i == 0) {
|
|
|
|
|
if (c1[i] == c2[j]) {
|
|
|
|
|
return 1;
|
|
|
|
|
} else {
|
|
|
|
|
return process(c1, c2, i, j - 1);
|
|
|
|
|
}
|
|
|
|
|
} else if (j == 0) {
|
|
|
|
|
if (c1[i] == c2[j]) {
|
|
|
|
|
return 1;
|
|
|
|
|
}else {
|
|
|
|
|
return process(c1, c2, i - 1, j);
|
|
|
|
|
}
|
|
|
|
|
}else {
|
|
|
|
|
int p1 = process(c1, c2, i - 1, j);
|
|
|
|
|
int p2 = process(c1, c2, i, j - 1);
|
|
|
|
|
int p3 = c1[i] == c2[j] ? 1 + process(c1, c2, i - 1, j - 1) : 0;
|
|
|
|
|
return Math.max(p1, Math.max(p2, p3));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static class Dp {
|
|
|
|
|
public static int longestCommonSubsequence(String s1, String s2) {
|
|
|
|
|
if (s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0) {
|
|
|
|
@ -95,4 +130,34 @@ public class LongestCommonSubsequence {
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
static class Dp1 {
|
|
|
|
|
public static int longestCommonSubsequence(String s1, String s2) {
|
|
|
|
|
if (s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0) {
|
|
|
|
|
return 0;
|
|
|
|
|
}
|
|
|
|
|
int n = s1.length();
|
|
|
|
|
int m = s2.length();
|
|
|
|
|
char[] c1 = s1.toCharArray();
|
|
|
|
|
char[] c2 = s2.toCharArray();
|
|
|
|
|
int[][] dp = new int[n][m];
|
|
|
|
|
dp[0][0] = c1[0] == c2[0] ? 1 : 0;
|
|
|
|
|
for (int j = 1; j < m; j++) {
|
|
|
|
|
dp[0][j] = c1[0] == c2[j] ? 1 : dp[0][j - 1];
|
|
|
|
|
}
|
|
|
|
|
for (int i = 1; i < n; i++) {
|
|
|
|
|
dp[i][0] = c1[i] == c2[0] ? 1 : dp[i - 1][0];
|
|
|
|
|
}
|
|
|
|
|
for (int i = 1; i < n; i++) {
|
|
|
|
|
for (int j = 1; j < m; j++) {
|
|
|
|
|
int p1 = dp[i - 1][j];
|
|
|
|
|
int p2 = dp[i][j - 1];
|
|
|
|
|
int p3 = c1[i] == c2[j] ? 1 + dp[i - 1][j - 1] : 0;
|
|
|
|
|
dp[i][j] = Math.max(p1, Math.max(p2, p3));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return dp[n - 1][m - 1];
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|