lintcode_79最长公共字串

本文介绍了一种求解两个字符串最长公共子串的方法,并通过一个具体的例子进行说明。使用Python实现,通过滑窗的方式遍历第二个字符串的所有可能子串,并在第一个字符串中查找是否存在这些子串。

给出两个字符串,找到最长公共子串,并返回其长度。

样例

给出A=“ABCD”,B=“CBCE”,返回 2

 

class Solution:
    """
    @param: A: A string
    @param: B: A string
    @return: the length of the longest common substring.
    """
    def longestCommonSubstring(self, A, B):
        # write your code here
        if not A:
            return 0
        result = -1
        for i in range(len(B)):
            for j in range(i,len(B)+1):
                result = max(j-i,result) if A.find(B[i:j])!=-1 else result
        return result

利用find方法滑窗式搜索,注意B[i:j] 实际为左闭右开区间,因此B的范围为range[i,len(B)+1]

转载于:https://www.cnblogs.com/zhangli-ncu/p/8011659.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值