First, let's look at a simple string match.
you can put the text string s fixed, the pattern string p from the S-aligned left edge, as the bearing part is exactly the same, the match succeeds, the failure will be the pattern string p overall to the right 1 locations, continue to check the Alignment section, repeat .
#朴素匹配def Naive_match (S, p): m = Len (s), n = Len (p) for I in range (m-n+1): #起始指针i if s[i:i+n] = = P: return T Rue return False
About the KMP algorithm, the best is the Nanyi of the string matching KMP algorithm; read it all the way.
The truth is,
preprocessing the pattern string p to get a partial matching table of the prefix, so that we can use the known information to figure out how many bits can be shifted to the right. that is, KMP = simple match + Mobile multi-bit.
A lot of other details please see Nanyi's article, this will not unfold.
The following is a Python code implementation.
#KMPdef Kmp_match (S, p): m = Len (s), n = Len (p) cur = 0# start pointer cur table = partial_table (p) while cur<=m-n : For i in range (n): if s[i+cur]!=p[i]: cur + = max (i-table[i-1], 1) #有了部分匹配表, we are not just simple 1-bit 1-bit to move to the right, to move multiple bits at once break Else: return True return false# partial match table Def partial_table (p): "' partial_table (" Abcdabd " ), [0, 0, 0, 0, 1, 2, 0] " prefix = set () postfix = set () ret = [0] for i in range (1,len (P)):
prefix.add (p[:i]) postfix = {p[j:i+1] for J in range (1,i+1)} ret.append (Len ((Prefix&postfix or {'}). Pop ())) return retprint naive_match ("BBC abcdab Abcdabcdabde", "Abcdabd") Print partial_table ("Abcdabd") print KMP _match ("BBC abcdab Abcdabcdabde", "ABCDABD")
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Flow Python-string KMP match