import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class MaxLen
{
//数组b用来跟踪c
//数组c[i][j]用来记录x[i]和y[j]的最长公共子序列大小
static int[][] b;
static int[][] c;
public static int IcsLength(char[]x,char[]y)
{
//lenx,leny分别用来记录两字串的长度
int lenx=x.length;
int leny=y.length;
c=new int[lenx+1][leny+1];
b=new int[lenx+1][leny+1];
//加入行c[0][j]列c[i][0]只是为了便于后面计算,所以将其初始化为0
for(int i=0;i<x.length;i++)
{
c[i][0]=0;
}
for(int j=0;j<y.length;j++)
{
c[0][j]=0;
}
//依次迭代计算出数组c的所有值,同时记录b
for(int i=0;i<lenx;i++)
for(int j=0;j<leny;j++)
{
if(x[i]==y[j])
{
c[i+1][j+1]=c[i][j]+1;
b[i+1][j+1]=1;
}
else if (c[i][j+1]>c[i+1][j])
{
c[i+1][j+1]=c[i][j+1];
b[i+1][j+1]=2;
}
else
{
c[i+1][j+1]=c[i+1][j];
b[i+1][j+1]=3;
}
}
return c[lenx][leny];
}
public static void Ics(char[]x,char[]y,int m,int n)
{
//递归出口
if(m<1||n<1)return;
else if(b[m][n]==1)
{
Ics(x,y,m-1,n-1);
System.out.print(x[m-1]);
}
else if(b[m][n]==2) Ics(x,y,m-1,n);
else Ics(x,y,m,n-1);
}
public static void main(String[]arg)throws IOException
{
//从控制台读取两个字串
System.out.println("输入第一个序列");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s= br.readLine();
char[]X= s.toCharArray();
System.out.println("输入第二个序列");
BufferedReader cr=new BufferedReader(new InputStreamReader(System.in));
s= br.readLine();
char[]Y= s.toCharArray();
//调用函数完成功能
System.out.println("最长公共子序列大小:"+IcsLength(X,Y));
System.out.print("最长公共子序列:");
Ics(X,Y,X.length,Y.length);
}
}
import java.io.InputStreamReader;
import java.io.IOException;
public class MaxLen
{
//数组b用来跟踪c
//数组c[i][j]用来记录x[i]和y[j]的最长公共子序列大小
static int[][] b;
static int[][] c;
public static int IcsLength(char[]x,char[]y)
{
//lenx,leny分别用来记录两字串的长度
int lenx=x.length;
int leny=y.length;
c=new int[lenx+1][leny+1];
b=new int[lenx+1][leny+1];
//加入行c[0][j]列c[i][0]只是为了便于后面计算,所以将其初始化为0
for(int i=0;i<x.length;i++)
{
c[i][0]=0;
}
for(int j=0;j<y.length;j++)
{
c[0][j]=0;
}
//依次迭代计算出数组c的所有值,同时记录b
for(int i=0;i<lenx;i++)
for(int j=0;j<leny;j++)
{
if(x[i]==y[j])
{
c[i+1][j+1]=c[i][j]+1;
b[i+1][j+1]=1;
}
else if (c[i][j+1]>c[i+1][j])
{
c[i+1][j+1]=c[i][j+1];
b[i+1][j+1]=2;
}
else
{
c[i+1][j+1]=c[i+1][j];
b[i+1][j+1]=3;
}
}
return c[lenx][leny];
}
public static void Ics(char[]x,char[]y,int m,int n)
{
//递归出口
if(m<1||n<1)return;
else if(b[m][n]==1)
{
Ics(x,y,m-1,n-1);
System.out.print(x[m-1]);
}
else if(b[m][n]==2) Ics(x,y,m-1,n);
else Ics(x,y,m,n-1);
}
public static void main(String[]arg)throws IOException
{
//从控制台读取两个字串
System.out.println("输入第一个序列");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s= br.readLine();
char[]X= s.toCharArray();
System.out.println("输入第二个序列");
BufferedReader cr=new BufferedReader(new InputStreamReader(System.in));
s= br.readLine();
char[]Y= s.toCharArray();
//调用函数完成功能
System.out.println("最长公共子序列大小:"+IcsLength(X,Y));
System.out.print("最长公共子序列:");
Ics(X,Y,X.length,Y.length);
}
}