public class LCSLength {
static int[][] c;
static int[][] b;
static char x[];
static char y[];
public static void lcsLength(String str1,String str2){
int i,j;
for(i=0;i<=str1.length();i++)
c[i][0]=0;
for(j=0;j<=str2.length();j++)
c[0][j]=0;
for(i=1;i<=str1.length();i++)
for(j=1;j<=str2.length();j++){
if(x[i-1]==y[j-1]){
c[i][j]=c[i-1][j-1]+1;
b[i][j]=1;
}else{
if(c[i-1][j]>=c[i][j-1]){
c[i][j]=c[i-1][j];
b[i][j]=2;
}else{
c[i][j]=c[i][j-1];
b[i][j]=3;
}
}
}
}
public 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);
}
public static void main(String[] args) {
String str1="jnavogak";
String str2="bjaova";
c=new int[str1.length()+1][str2.length()+1];
b=new int[str1.length()+1][str2.length()+1];
x = str1.toCharArray();
y = str2.toCharArray();
lcsLength(str1,str2);
System.out.println("最长公共子序列长度:"+ c[str1.length()][str2.length()]);
LCS(str1.length(),str2.length(),x,b);
}
}
最长公共子序列长度:4
java