import java.util.LinkedList;
public class LCS {
public static int getLengthOfLCS(int record[][], String s1, String s2) {
int matrix[][] = new int[s1.length() + 1][s2.length() + 1];
for (int i = 0; i <= s1.length(); i++) {
for (int j = 0; j <= s2.length(); j++) {
matrix[i][j] = 0;
}
}
for (int i = 1; i <= s1.length(); i++) {
for (int j = 1; j <= s2.length(); j++) {
if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1] + 1;
record[i][j] = 1;// 1代表由斜上方值加1
} else {
if (matrix[i][j - 1] >= matrix[i - 1][j]) {
matrix[i][j] = matrix[i][j - 1];
record[i][j] = 2;// 2代表由左侧值得出
} else {
matrix[i][j] = matrix[i - 1][j];
record[i][j] = 3;// 3代表由正上方值得出
}
}
}
}
return matrix[s1.length()][s2.length()];
}
public static void printLCS(int record[][], String s1, int row, int col) {
LinkedList<Character> myStack = new LinkedList<>();
int i = row - 1;
int j = col - 1;
while (i > 0 && j > 0) {
if (record[i][j] == 1) {
myStack.push(s1.charAt(i - 1));
i--;
j--;
} else if (record[i][j] == 2) {
j--;
} else if (record[i][j] == 3) {
i--;
}
}
while (!myStack.isEmpty()) {
System.out.print(myStack.pop() + " ");
}
}
public static void main(String[] args) {
String s1 = "abddddc";
String s2 = "cabc";
int record[][] = new int[s1.length() + 1][s2.length() + 1];
for (int i = 0; i <= s1.length(); i++) {
for (int j = 0; j <= s2.length(); j++) {
record[i][j] = 0;
}
}
System.out.println("最长公共子序列长度为: " + getLengthOfLCS(record, s1, s2));
printLCS(record, s1, s1.length() + 1, s2.length() + 1);
}
}
最长公共子序列Java
最新推荐文章于 2023-06-04 23:23:44 发布