kmp-string pattern matching-python implementation

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.