1. 程式人生 > >KMP-字符串模式匹配-python實現

KMP-字符串模式匹配-python實現

spa 分享 ext ima raw_input [] sel span pre

KMP算法可以在O(n+m)的時間數量級上完成模式匹配,其做法在於:沒當一次匹配過程中出現字符比較不等時,不需要回溯指針,而是利用已經得到的“部分匹配”的結果將模式向右“滑動”盡可能遠的一段距離後,繼續進行比較。

在KMP算法中主要是先得到子字符串的next數組,比如子字符串為:abaabcac,計算如下圖

技術分享圖片

得到子字符串之後,在字符串匹配的時候,子字符串不再是移動1個字符串,而是移動next(j)個位置,代碼如:(這裏需要註意,next數組是從1開始的,沒有0)

#-*- coding:utf-8 -*-

class KMP:

    def __init__(self,s_long,s_short):
        self.s_long
=s_long self.s_short=s_short self.flag=0 def get_nextList(self): l=[0,1] for i in range(2,len(self.s_short)): l.append(self.get_num_1(self.s_short[0:i])) print l b=0 a=0 while True: if self.s_short[a]==self.s_long[b]: a
+=1 b+=1 else: a=l[a]-1 if a==-1: a += 1 b += 1 if self.s_short==self.s_long[b:b+len(self.s_short)]: break if b==len(self.s_long): return 0
return b+1 ‘‘‘ 功能(見圖2、3):獲得子字符串的next數組,和第一張圖方法比一樣,更容易理解 s:用於存儲該字符前面所有的子字符串(註意子字符串是從這個字符串開始從後往前,長度慢慢增長) while循環:用於確定前面最長重復的字符串(註意,應該從長的開始匹配,且必須從第一個字符開始) 返回最長字符串長度+1 ‘‘‘ def get_num_1(self,string): s=[] for i in range(1,len(string)): s.append(string[len(string)-i:len(string)]) while s: temp=s.pop() n=len(temp) if temp==string[0:n+0]: return len(temp)+1 return 1 long=raw_input() short=raw_input() print KMP(long,short).get_nextList()

技術分享圖片

技術分享圖片

KMP-字符串模式匹配-python實現