python实现KMP算法原理

01.前置知识:字符串的前缀与后缀


如thank,
其前缀有:t,th,tha,than,thank
后缀有:thank,hank,ank,nk,k

02.KMP算法思想及执行流程


思想:每一趟比较中出现字符不等时,利用已经得到的部分匹配的结果将子串向右滑动尽可能远的距离,继续进行比较。 

注意:kmp算法中,找的最长公共前后缀:长度要小于比较指针左端子串长度

03.求模式串的next数组


找最长公共前后缀(长度要小于比较指针左端子串长度)

3.1案例分析
案例1:abbabaababaa


next数组为:[0, 0, 1, 2, 3, 1, 1, 2, 3]

以上参考:https://blog.csdn.net/qq_46237746/article/details/122788832

3.2 实现Leecode字符串匹配python代码

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        a = len(haystack)
        b = len(needle)
        if b == 0:
            return 0
        next = self.getnext(b,needle)    #先匹配needle里面每一位最大公共前缀和后缀的个数
        j=0
        for i in range(a):
            while haystack[i]!=needle[j] and j>0:
                j = next[j-1]           # 若不相等,则跳转的步长为不匹配的索引的前一个next
            if haystack[i]==needle[j]:
                j += 1
            if j == b:               #判断是否遍历完模式串needle
                return i-b+1
        return -1
 
    def getnext(self,b,needle):    #得到next数组
        j = 0
        next = [0 for x in range(b)]
        for i in range(1,b):
            while(j > 0 and needle[j]!=needle[i]):    #当首字母匹配后第二个匹配不上,直接让j                    
                                                               变成首字母重新匹配
                j = next[j-1]
            if needle[j]==needle[i]:        #一直找到一个与首字符相同的字符才更新j索引
                j += 1
            next[i] = j
        return next


 

猜你喜欢

转载自blog.csdn.net/m0_55780358/article/details/127221202