python KMP算法

参考博文:

https://blog.csdn.net/v_july_v/article/details/7041827

原文讲的比较全面,加上图解,理解起来也不是很难。

这里采用了优化后的next数组,难点在于next数组的求解,而个人认为next数组求解时递归的部分可能要稍微难理解一点。

具体讲解参考原博,下面是python版本的KMP算法。

class Solution:
    # 字符串匹配,匹配成功返回目标串中第一次出现的下标,失败返回-1
    def KMP(self, target, pattern):
        next = self.getNext(pattern)
        print(next)
        i = j = 0
        while i < len(target) and j < len(pattern):
            # i不存在回溯,匹配则i加1,否则移动模式串j的位置以匹配目标串
            if j == -1 or target[i] == pattern[j]:
                i += 1 
                j += 1
            else:
                j = next[j]
        if j == len(pattern):
            return i-j
        else:
            return -1
                
    # 计算next数组
    def getNext(self,pattern):
        next = [0]*len(pattern)
        next[0] = -1
        k = -1 # 前缀结束索引
        j = 0  # 后缀结束索引
        while j < len(pattern)-1: 
            if k == -1 or pattern[k] == pattern[j]:
                k += 1
                j += 1
                if pattern[k] == pattern[j]:
                    next[j] = next[k]
                else:
                    next[j] = k
            else:
                k = next[k] # 寻找更短的后缀
        return next
    
if __name__ == '__main__':
    p = Solution()
    target = input('Enter the target string:')
    pattern = input('Enter the pattern string:')
    while pattern != '-1':       
        print(p.KMP(target, pattern))
        pattern = input('Enter the pattern string:')

你可能感兴趣的:(python KMP算法)