用例:
输入:
ABCBDAB
BDCABA
输出:
最长子序列的长度是:4
最长子序列是:BCBA
import java.util.Scanner;
public class LCS {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[][]b=new int[100][100];
String s1 = sc.nextLine();
String s2 = sc.nextLine();
int x = lcsLength(s1.toCharArray(),s2.toCharArray(),b);
System.out.print("最长子序列的长度是:");
System.out.println(x);
System.out.println("--------------------------");
System.out.print("最长子序列是:");
int len1 = s1.length();
int len2 = s2.length();
lcs(len1,len2,s1.toCharArray(),b);
}
private static void lcs(int i, int j, char[] x, int[][] b) {
if(i==0 || j==0)
return ;
if(b[i][j]==1)
{
lcs(i-1,j-1,x,b);
System.out.print(x[i-1]);
}
else if(b[i][j]==2)
lcs(i-1,j,x,b);
else
lcs(i,j-1,x,b);
}
private static int lcsLength(char[] a, char[] b, int[][] c) {
int len1 = a.length;
int len2 = b.length;
//len(i,j)表示a左边i个字符和b左边j个字符的最长公共子序列
int[][] len = new int[len1+1][len2+1];
//有点多余
for(int i=0;i<=len1;i++) len[i][0]= 0;
for(int i=0;i<=len2;i++) len[0][i]=0;
for(int i=1;i<=len1;i++)
{
for(int j=1;j<=len2;j++)
{
//len(i,j)表示a左边i个字符和b左边j个字符的最长公共子序列
//a左边1个字符 b左边1个字符形成的公共子序列
//判断他们最右字符a[i-1]和b[j-1]是否相等
if(a[i-1]==b[j-1])
{
len[i][j]=len[i-1][j-1]+1;
c[i][j]=1;
}
else if(len[i-1][j]>=len[i][j-1]){
len[i][j]=len[i-1][j];
c[i][j]=2;
}
else
{
len[i][j]=len[i][j-1];
c[i][j]=3;
}
}
}
return len[len1][len2];
}
}