动态规划---最长公共子序列

public class LCSLength {

    static int[][] c;//c[i][j]存储Xi和Yj的最长公共子序列长度
    static int[][] b;//b[i][j]记录c[i][j]的值是由哪一个子问题 解得到的
    static char x[];//将第一个字符串转换为字符数组存储在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);
        //最长长度为数组c最后一个位置数字
        System.out.println("最长公共子序列长度:"+ c[str1.length()][str2.length()]);
        //递归输出
        LCS(str1.length(),str2.length(),x,b);
    }
}
最长公共子序列长度:4
java
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值