牛客 BM66 最长公共子串 【动态规划】

该文介绍了如何使用动态规划方法解决找到两个字符串的最长公共子串问题。算法的时间复杂度和空间复杂度均为O(n^2),其中n为字符串的长度。初始思路是使用二维数组存储中间状态,但考虑到子串的连续性,可以优化为一维数组降低空间复杂度。
摘要由CSDN通过智能技术生成

描述

给定两个字符串str1和str2,输出两个字符串的最长公共子串

题目保证str1和str2的最长公共子串存在且唯一。 

数据范围: 1str1,str25000

要求: 空间复杂度O(n2),时间复杂度O(n2)

示例1

输入:

"1AB2345CD","12345EF"

返回值:

"2345"

 dp背包问题

s1 = "1AB2345CD"

s2 = "12345EF"

当 s1 的 xPos 位置 = s2 的 yPos 的字符时,它的最大长度等于 dp[yPos-1][xPos-1] + 1,那么 dp 公式就出来了

    public String LCS (String str1, String str2) {
        // write code here
        if (str1 == null || str2 == null || str1.isEmpty() || str2.isEmpty()) {
            return "";
        }
        int length1 = str1.length();
        int length2 = str2.length();
        int[][] dpMap = new int[length2][length1];
        int xPos;
        int yPos;
        int maxXPos = 0;
        int maxLength = 0;
        // 初始化 dpMap
        for (xPos = 0; xPos < length1; xPos++) {
            char c = str2.charAt(0);
            if (c == str1.charAt(xPos)) {
                dpMap[0][xPos] = 1;
            }
        }
        for (yPos = 1; yPos < length2; yPos++) {
            char c = str1.charAt(0);
            if (c == str2.charAt(yPos)) {
                dpMap[yPos][0] = 1;
            }
        }
        for (yPos = 1; yPos < length2; yPos++) {
            for (xPos = 1; xPos < length1; xPos++) {
                if (str1.charAt(xPos) == str2.charAt(yPos)) {
                    int temp = dpMap[yPos-1][xPos-1] + 1;
                    dpMap[yPos][xPos] = temp;
                    if (temp > maxLength) {
                        maxXPos = xPos;
                        maxLength = temp;
                    }
                }
            }
        }
        return str1.substring(maxXPos-maxLength+1, maxXPos+1);
    }

 二维背包时间复杂度 O(n^2),空间复杂度 O(n^2)。但因为本体的特殊性,子串是连续的字符串,所以可以用反向的一维数组代替。

即 dp[xPos] = dp[xPos-1] + 1

此处 dp[xPos] 是这个循环的当前位置,而 dp[xPos-1] 是上个循环的当前位置

        for (yPos = 1; yPos < length2; yPos++) {
            for (xPos = length1-1; xPos >= 0; xPos--) {
                if (str1.charAt(xPos) == str2.charAt(yPos)) {
                    int temp = dpMap[xPos] + 1;
                    dpMap[xPos+1] = temp;
                    if (temp > maxLength) {
                        maxXPos = xPos;
                        maxLength = temp;
                    }
                } else {
                    dpMap[xPos+1] = 0;
                }
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值