Implement strStr()

地址:点击打开链接

这道题就是求一个字符串是否是另一个字符串的子字符串,所以第一种方法首先想到的是KMP算法,其次用暴力破解,还有用素数代表字符,然后根据进位来计算相关和的方法,

但是容易发生溢出,所以就需要采用,大数值或者用KMP算法,这里python的数值好像溢出了,所以就采用KMP,看了两天,里面难点是next数组的求法,具体求法参见july的博客


答案:

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0
        if not haystack and needle:
            return -1
        haystackLength = len(haystack)
        next = self.getNextArr(needle)
        needleLength = len(needle)
        j = 0
        k = 0
        while j < haystackLength  and k < needleLength:
            if k == -1 or haystack[j] == needle[k]:
                j += 1
                k += 1
            else:
                k = next[k]
        if k == needleLength:
            return j - k
        else:
            return -1


    def getNextArr(self,s):
        arrLength = len(s)
        k = -1
        j = 0
        next = [ i for i in range(arrLength)]
        next[0] = -1
        while j < arrLength - 1:
            if k == -1 or s[k] == s[j]:
                k += 1
                j += 1
                next[j] = k
            else:
                k = next[k]
        return next


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值