Elegant python-kmp matching algorithm for strings

Source: Internet
Author: User

First, let's look at the simple matching of strings.

It can be imagined that the text string s is fixed, the pattern string p from the left edge of the alignment, if the alignment of the part is exactly the same, then the match succeeds, the failure will be the pattern string p overall to the right 1 bits, continue to check the alignment portion, so repeated .

#朴素匹配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.
is actually, 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 + move multi-bit.
For more details please see Nanyi's article, which will not unfold here.
The code implementation for Python is given below.

#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 the right, you can 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")


Elegant python-kmp matching algorithm for strings

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.