public class Main {
public static void main(String[] args) {
String wordA = "hsfdiauhfbfddddsdfcasfsad";
String wordB = "fasdfgsaddddfsdjihfsdaf";
StringBuilder longestCommonSequence = new StringBuilder();
int length = getLongestCommonSequence(wordA, wordB, longestCommonSequence);
System.out.println("最长公共序列的长度为 " + length);
System.out.println(longestCommonSequence);
System.out.println("----------------------");
wordA = "dfgdfsdfg";
wordB = "fasdwefwfaefs";
longestCommonSequence = new StringBuilder();
length = getLongestCommonSequence(wordA, wordB, longestCommonSequence);
System.out.println("最长公共序列的长度为 " + length);
System.out.println(longestCommonSequence);
}
public static int getLongestCommonSequence(String wordA, String wordB, StringBuilder sequence) {
int lengthA = wordA.length();
int lengthB = wordB.length();
if (lengthA == 0 || lengthB == 0) {
System.out.println("Please check the words you entered.");
return -1;
}
int[][] dpArray = new int[lengthA + 1][lengthB + 1];
for (int i = 1; i <= lengthA; i++) {
for (int j = 1; j <= lengthB; j++) {
if (Character.toUpperCase(wordA.charAt(i - 1)) == Character.toUpperCase(wordB.charAt(j - 1))) {
dpArray[i][j] = dpArray[i - 1][j - 1] + 1;
} else {
dpArray[i][j] = Math.max(dpArray[i - 1][j], dpArray[i][j - 1]);
}
}
}
int maxLength = dpArray[lengthA][lengthB];
int i = lengthA, j = lengthB;
while (i > 0 && j > 0) {
if (Character.toUpperCase(wordA.charAt(i - 1)) == Character.toUpperCase(wordB.charAt(j - 1))) {
sequence.insert(0, Character.toUpperCase(wordA.charAt(i - 1)));
i--;
j--;
} else if (dpArray[i - 1][j] > dpArray[i][j - 1]) {
i--;
} else {
j--;
}
}
return maxLength;
}
}