leetcode--28. 实现strStr()

题目:28. 实现strStr()

链接:https://leetcode-cn.com/problems/implement-strstr/description/

在字符串haystack中寻找子串needle第一次出现的位置,若匹配失败返回-1。

其实就是python字符串的find方法。下面是一个KMP算法:

python:

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0
        def getNext(str):
            length = len(str)
            next = [-1 for i in range(length + 1)]
            j, k = 0, -1
            while j < length:
                if k == -1 or str[j] == str[k]:
                    j, k = j + 1, k + 1
                    next[j] = k
                else:
                    k = next[k]
            return next

        def KMP(s, p):
            next = getNext(p)
            j = k = 0
            length = len(s)
            while j < length:
                if s[j] == p[k] or k == -1:
                    j += 1
                    k += 1
                else:
                    k = next[k]
                if k == len(p):
                    return j - k
            return -1
        return KMP(haystack,needle)
        # return (haystack.find(needle))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值