Flow Python-string KMP match

Source: Internet
Author: User

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

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.