利用动态规划和递归分别求两个串的最大公共子序列

本文介绍使用递归与动态规划两种方法求解两个字符串的最大公共子序列问题,并提供了具体的Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用动态规划和递归分别求两个串的最大公共子序列

这里写图片描述
相关代码

/*
 * 求两个子串的最大公共子序列      
 */
public class Msin {
    /*
     * 1.利用递归的思想来处理的求最大公共子序列
     */
    public static int f(String str, String str2){
        if(str.length() == 0 || str2.length() == 0) return 0;

        if(str.charAt(0) == str2.charAt(0))
            return f(str.substring(1),str2.substring(1)) + 1;
        else
            return Math.max(f(str.substring(1), str2), f(str, str2.substring(1)));
    }

    /*
     * 2.利用动态规划来解决问题减小了时间复杂度
     */
    public static int LCS(String str1, String str2){
        int[][] c = new int[str1.length()+1][str2.length()+1];  //建立矩阵
        for(int row=0; row<=str1.length(); row++){
            c[row][0] = 0;
        }
        for(int col=0; col<=str2.length(); col++){
            c[0][col] = 0;
        }
        //关键代码
        for(int i=1; i<=str1.length(); i++){
            for(int j=1; j<=str2.length(); j++){
                if(str1.charAt(i-1) == str2.charAt(j-1)){
                    c[i][j] = c[i-1][j-1] + 1;
                }else if(c[i][j-1] > c[i-1][j]){
                    c[i][j] = c[i][j-1];
                }else{
                    c[i][j] = c[i-1][j];
                }
            }
        }
        return c[str1.length()][str2.length()];
    }
    public static void main(String[] args) {
        int result = LCS("ABCBDAB", "BDCADA");
        System.out.println(result);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值