珍宝鸭的力扣练习(1):KMP算法实现strstr()函数

题目:给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例:
输入: haystack = “hello”, needle = “ll”
输出: 2

KMP算法:分为两部分,b数组 和 正式匹配

b数组 部分:找每个字符前的 最大相等前后缀长度:
比如 aba --> 一个前缀是 a,一个后缀是 a,最大相等前后缀长度 为 1
比如 baba --> 一个前缀是 ba,一个后缀是 ba,最大相等前后缀长度 为 2
比如 ababa --> 一个前缀是 aba,一个后缀是 aba,最大相等前后缀长度 为 3
图示即为b数组的创建。
珍宝鸭的力扣练习(1):KMP算法实现strstr()函数_第1张图片

代码部分:

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if len(needle)==0:
            return 0
        b=self.Creat_btable(needle)
        
        j,i=0,0
        while (j < len(haystack)):
            if (needle[i] == haystack[j]):
                i=i+1
                j = j + 1
            elif (i >0 and needle[i] != haystack[j]) :
                i=b[i]
            elif(i==0 and needle[i] != haystack[j]):
                j = j + 1
            if i==len(needle):
                return j-len(needle)

        return -1
    def Creat_btable(self, needle):
        j = -1
        i = 0  # j在后面,i在前面
        b=[j]
        while (i < len(needle)):
            while (j >= 0 and needle[i] != needle[j]):
                j = b[j]
            i=i+1
            j=j+1
            b.append(j)
        return b

你可能感兴趣的:(珍宝鸭的力扣练习(1):KMP算法实现strstr()函数)