Leetcode原题链接
https://leetcode.cn/problems/longest-common-subsequence/
public class CommonSubsequence {
public static int longestCommonSubsequence1(String s1, String s2) {
if (s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0) {
return 0;
}
char[] str1 = s1.toCharArray();
char[] str2 = s2.toCharArray();
return process1(str1, str2, str1.length - 1, str2.length - 1);
}
private static int process1(char[] str1, char[] str2, int i, int j) {
if (i == 0 && j == 0) {
return str1[i] == str2[j] ? 1 : 0;
} else if (i == 0) {
if (str1[i] == str2[j]) {
return 1;
} else {
return process1(str1, str2, i, j - 1);
}
} else if (j == 0) {
if (str1[i] == str2[j]) {
return 1;
} else {
return process1(str1, str2, i - 1, j);
}
} else {
int p1 = process1(str1, str2, i - 1, j);
int p2 = process1(str1, str2, i, j - 1);
int p3 = str1[i] == str2[j] ? 1 + process1(str1, str2, i - 1, j - 1) : 0;
return Math.max(Math.max(p1, p2), p3);
}
}
public static int longestCommonSubsequence2(String s1, String s2) {
if (s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0) {
return 0;
}
char[] str1 = s1.toCharArray();
char[] str2 = s2.toCharArray();
int[][] dp = new int[s1.length()][s2.length()];
dp[0][0] = str1[0] == str2[0] ? 1 : 0;
for (int i = 1; i < s1.length(); i++) {
dp[i][0] = str1[i] == str2[0] ? 1 : dp[i - 1][0];
}
for (int j = 1; j < s2.length(); j++) {
dp[0][j] = str1[0] == str2[j] ? 1 : dp[0][j - 1];
}
for (int i = 1; i < s1.length(); i++) {
for (int j = 1; j < s2.length(); j++) {
int p1 = dp[i - 1][j];
int p2 = dp[i][j - 1];
int p3 = str1[i] == str2[j] ? 1 + dp[i - 1][j - 1] : 0;
dp[i][j] = Math.max(p1, Math.max(p2, p3));
}
}
return dp[str1.length - 1][str2.length - 1];
}
public static int longestCommonSubsequence3(String s1, String s2) {
if (s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0) {
return 0;
}
char[] str1 = s1.toCharArray();
char[] str2 = s2.toCharArray();
int[] dp = new int[str1.length];
dp[0] = str1[0] == str2[0] ? 1 : 0;
for (int i = 1; i < s1.length(); i++) {
dp[i] = str1[i] == str2[0] ? 1 : dp[i - 1];
}
for (int col = 1; col < str2.length; col++) {
int temp = dp[0];
dp[0] = str1[0] == str2[col] ? 1 : temp;
for (int row = 1; row < str1.length; row++) {
int p1 = dp[row - 1];
int p2 = dp[row];
int p3 = str1[row] == str2[col] ? temp + 1 : 0;
temp = dp[row];
dp[row] = Math.max(Math.max(p1, p2), p3);
}
}
return dp[str1.length - 1];
}
public static void main(String[] args) {
System.out.println(longestCommonSubsequence2("abcde", "ace"));
System.out.println(longestCommonSubsequence3("abc", "def"));
}
}