leetcode 718 最长公共子串

给两个整数数组 nums1 和 nums2 ,返回 两个数组中 公共的 、长度最长的子数组的长度 。

示例 1:

输入:nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
输出:3
解释:长度最长的公共子数组是 [3,2,1] 。
示例 2:

输入:nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
输出:5

首先考虑暴力法,用前缀或后缀的思路,枚举nums1[i] 和 nums2[j],求以他们为结尾的字符串nums1[:i+1] 和 nums2[:j+1]的最长公共后缀,在所有枚举结果里面取最大值。时间复杂度O(n3)

# class Solution(object):
#     def findLength(self, nums1, nums2):
#         """
#         :type nums1: List[int]
#         :type nums2: List[int]
#         :rtype: int
#         """
#         tot = 0
#         for i in range(len(nums1)):
#             for j in range(len(nums2)):
#                 k = 0
#                 while (i + k < len(nums1)) and (j + k < len(nums2)) and (nums1[i+k] == nums2[j+k]):
#                     k += 1
#                 tot = max(tot, k)
#         return tot 
class Solution(object):
    def findLength(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: int
        """
        tot = 0
        for i in range(len(nums1)):
            for j in range(len(nums2)):
                k = 0
                while (i - k >= 0) and (j - k >= 0) and (nums1[i-k] == nums2[j-k]):
                    k += 1
                tot = max(tot, k)
        return tot 

可以看出复杂度高的原因是,nums1[i]和nums2[j]不断被重复比较,如果想比较一次,以后就直接不用比较了,那么就考虑动态规划。和子序列不一样的是’abc’ 与’abd’最长公共子串为’ab’,长度为2,但是添加一位以后,‘abcd’与’abdd’即便最后一位相同,这个最长子串的长度依然还是2. 所以我们的dp[i][j]的含义要变一下,就是分别以nums1[i-1]和nums2[j-1]结尾的字符串的最长公共后缀,最终结果就是所有dp[i][j]取值中的最大值。

状态转移方程,分两种考虑:
当 text1[i - 1] == text2[j - 1] 时,说明两个字符串的最后一位相等,所以最长公共后缀又增加了 1,即 dp[i][j] = dp[i - 1][j - 1] + 1;
当 text1[i - 1] != text2[j - 1] 时,说明两个子串的最后一位不相等,此时字符串的最长公共后缀为0,即 dp[i][j] =0

dp[0][…]和dp[…][0]代表其中一个是空字符串,最长公共后缀长度为0,据此设置边界条件

最后一位如果不同,则dp[-1][-1]=0,但是两个字符串仍然可能是有公共子串的,因此我们需要用一个变量来记录最大值,而不是return dp[-1][-1]

class Solution(object):
    def findLength(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: int
        """
        tot = 0
        dp = [[0]*(len(nums2)+1) for _ in range(len(nums1)+1)]
        for i in range(1, len(nums1)+1):
            for j in range(1, len(nums2)+1):
                if nums1[i-1] == nums2[j-1]:
                    dp[i][j] = dp[i-1][j-1] + 1
                else:
                    dp[i][j] = 0 
                tot = max(tot, dp[i][j])
        return tot 

时间复杂度O(m Xn ), 空间复杂度O(m x n)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值