最长公共子序列
程序员文章站
2024-03-17 22:00:22
...
public class Lcs {
public static int LcsLength(String[] x, String[] y, int [][]b)
{
int m =x.length-1;
int n=y.length-1;
int [][]c = new int [m+1][n+1];
for(int i=1;i<=m;i++)c[i][0]=0;
for(int i=1;i<=n;i++)c[0][i]=0;
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++) {
if(x[i]==y[j]) {
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;
}
}
return c[m][n];
}
public static void lcs(int i,int j,String[] x,int [][]b)
{
if(i==0||j==0)return;
if(b[i][j]==1) {
lcs(i-1, j-1, x, b);
System.out.println(x[i]);
}
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[]) {
System.out.println("测试结果:");
String[] x = {" ","A", "B", "C", "B", "D", "A", "B"};
String[] y = {" ","B", "D", "C", "A", "B", "A"};
int[][] b = new int[x.length][y.length];
int c = LcsLength(x, y,b);
System.out.println("X和y的最长公共子序列是:");
lcs(x.length - 1, y.length - 1,x,b);
}
}
上一篇: STL:multiset
下一篇: Lua 模拟面向对象