话不多说,直接贴代码和运行结果图。有问题评论区留言
package 动态规划;
import java.util.Scanner;
/**
* @author LzStart
* @create 2022-03-20-21:47
*/
public class The_LCS {//求最长公共子序列
public static void theLongestCommonSubsequences(char[] a, char[] b) {
int n = a.length;
int m = b.length;
int[][] L = new int[n][m];
//初始化二维表 L 的第一行第一列为 0
for (int i = 0; i < n; i++) {
L[i][0] = 0;
}
for (int j = 0; j < m; j++) {
L[0][j] = 0;
}
//LCS算法
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
if (a[i] == b[j]) {
L[i][j] = L[i - 1][j - 1] + 1;
} else {
L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]);
}
}
}
System.out.println("LCS长度为:" + L[n - 1][m - 1]);
//反向寻找LCS
//1.将LCS放在 arr 数组中
int len = Math.min(n, m);// arr 数组长度
char[] arr = new char[len];
//2. k,s 指向 L 的最后一个元素,反向寻找LCS
int k = n - 1;
int s = m - 1;
int r = 0;
//3.反向寻找过程
while(L[k][s] != 0){// L[K][S] 为 0 的时候结束寻找
if(a[k] == b[s]){// 当 a[k] == b[s] 的时候,此时的L[k][s] 是左上一位加一得到的
arr[r++] = a[k];
k--;
s--;
}else{
if(L[k][s] == L[k - 1][s] && L[k][s] == L[k][s - 1]){//此时的L[k][s] 是左边或者上边的最大值得到的
k--;
}else if(L[k][s] > L[k - 1][s]){
s--;
}else if(L[k][s] > L[k][s - 1]){
k--;
}
}
}
//4.输出LCS
System.out.print("LSC--->");
for (int i = r - 1; i >= 0; i--) {//得到的arr数组反向输出,即为LCS
System.out.print(arr[i] + " ");
}
System.out.println();
//打印二维表 L
System.out.print(" ");
for (int i = 0; i < m; i++) {
System.out.print(b[i] + " ");
}
System.out.println();
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
for (int j = 0; j < m; j++) {
System.out.print(L[i][j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("输入A:");
String A = scanner.nextLine();
System.out.print("输入B:");
String B = scanner.nextLine();
char[] a = new char[A.length() + 1];
char[] b = new char[B.length() + 1];
a[0] = ' ';
b[0] = ' ';
for (int i = 0; i < A.length(); i++) {
a[i + 1] = A.charAt(i);
}
for (int i = 0; i < B.length(); i++) {
b[i + 1] = B.charAt(i);
}
theLongestCommonSubsequences(a, b);
}
}