Python KMP string match

Source: Internet
Author: User

First of all, I rookie one, write a blog is to record the process of learning, as well as their own understanding and experience, there may be a bad place to write, I hope the great God pointed out ...

Throw a question

Given a text string Test_str (a matched string) and a pattern string pat_str (a string that needs to be matched from a text string), find out where the pattern string pat_str first appears from the text string test_str, and return no-1

Violent ways

Before we say KMP, let's start with the "violent way", that is, our most primitive method.

  

Text_str ='Asdabcdace'Pat_str='Abcdace'defStr_match (TEXT_STR,PAT_STR): forIinchRange (0,len (TEXT_STR)): J= 1 whileJ <Len (pat_str):ifTEXT_STR[I:I+J]! = Pat_str[0:j]:#starting with TEXT_STR, see if the match is successful                 Break   #match fails, jumps directly out of the loop, i+1, continues to match from the first characterJ + = 1#match succeeds to match next character, knowing pat_str each character matches        ifj = =Len (pat_str):returnIreturn-1Print(Str_match (TEXT_STR,PAT_STR))

It is called the brute force solution, because each time the match fails, the pattern string is moved backwards, and the match starts from the beginning, and the loop continues. resulting in a high degree of time complexity, KMP is to optimize this place, each time the match fails, the next move distance next value

Kmp

If I were to give you a complete understanding of the KMP algorithm may not be easy, I can only roughly approximate the next step of the implementation. I think it's a point,

  How to find the next value for each character of the pattern string

Because it is possible that each time a match fails, the length of the character is different, and the distance from each move is different, so how do we ask for the next value of each character, which leads to another concept

    maximum prefix and maximum suffix

    

  Assuming the maximum prefix = maximum suffix, the length is K then the first character, the corresponding next value is K+1, a loop can find the next value of each character

Code implementation

  

#to find the next value of a stringText_str ='Asdabcdace'Pat_str='Abcdace'#get the next value corresponding to the characterdefStr_next (s):#The first two characters are equal to 1 by defaultNext = []     forXinchRange (2, Len (s)): Next.append (str_max_prx (s,x,next[x-1]-1) + 1)    returnNext#The parameter s string, where the match is made, and the next match begins .defstr_max_prx (s,x,last_value): Next=0 forIinchRange (last_value,x):ifS[0:I] = = s[x-i:x]: Next=IreturnNextdefStr_match (s,m): Next=Str_next (s) I=0 S_len=Len (s) M_len=Len (m) whileI <=M_len:flag= True#flag bit, used to determine if the match was successfulindex = 1 whileIndex <=S_len:ifM[I:I + index]! =S[0:index]: I= i +Next[index] Flag=False Break            Else: Index+ = 1ifflag: Break    ifI >=m_len:i=-1returnIres=Str_match (PAT_STR,TEXT_STR)Print(RES)

This is the code, and many things may need to be understood. I take a note, for the convenience of later search, hope to you can help.

Python KMP string match

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.