The KMP algorithm can perform pattern matching at the time Order of O (n+m), in the way that it does not require a backtracking pointer when there are no differences in character comparisons during a match, but instead uses the result of the "partial match" that has been obtained to "slide" the pattern to the right as far as possible after the comparison.
In the KMP algorithm is the first to get the sub-string of next array, such as substring: ABAABCAC, calculated as
After the substring is obtained, when the string matches, the substring no longer moves 1 strings, but moves next (j) where the Codeis: (note here that the next array starts from 1, not 0)
#-*-coding:utf-8-*-classKMP:def __init__(self,s_long,s_short): Self.s_long=S_long Self.s_short=S_short Self.flag=0defget_nextlist (self): l=[0,1] forIinchRange (2, Len (self.s_short)): L.append (Self.get_num_1 (self.s_short[0:i]))PrintL B=0 A=0 whileTrue:ifself.s_short[a]==Self.s_long[b]: a+=1b+=1Else: A=l[a]-1ifA==-1: A+ = 1b+ = 1ifself.s_short==self.s_long[b:b+Len (self.s_short)]: Break ifb==Len (self.s_long):return0returnB+1" "function (see Figure 2, 3): Get the next array of substrings, as compared to the first graph method, it is easier to understand S: used to store all the substrings in front of the character (note that the substring starts from behind and slowly increases in length) While loop: the string used to determine the longest previous repetition (note that it should be matched from a long start and must begin with the first character) to return the longest string length +1" " defget_num_1 (self,string): s=[] forIinchRange (1, Len (String)): S.append (String[len (String)-I:len (String)]) whiles:temp=S.pop () n=Len (temp)iftemp==string[0:n+0]:returnLen (temp) +1return1Long=raw_input () short=raw_input ()PrintKMP (Long,short). Get_nextlist ()
kmp-string pattern matching-python implementation