Pattern matching algorithm

Source: Internet
Author: User
simple pattern matching algorithmBF algorithm (Brute-force, also known as classical, classic, simple, exhaustive) with backtracking, speed slow algorithm matching process complexity is O (m*n) (n,m respectively for the target string and the length of the pattern string)

Algorithm design idea: The target string T of the first POS characters and mode p of the 1th character comparison, if equal, continue to compare the subsequent characters, if not, from the next character of the target string T (pos+1), again with the P of the second character comparison. Until the sequence of one consecutive substring of the target string T is equal to mode p. Returns the ordinal number of the first character of a substring in t that matches a p, that is, the match succeeds. Otherwise, the match fails, and the return value is 0.

Algorithm implementation code:

int find (char* target, char* Pat) {//target: target string  Pat: pattern string
     int i=0,j=0;
     int LENGTHP =strlen (PAT),   lengtht =strlen (target);
     while (I<=LENGTHT-LENGTHP) {           
        j=0;
        while (TARGET[I]==PAT[J]&&J<LENGTHP) {
                i++;
                j + +;
        } 
        if (J==LENGTHP) return  i-j///String Pat finished scan, match success
        else i=i-j+1;//mismatch, make next trip compare
     }
     return–1; 
}
KMP (knuth-morris-pratt) algorithmTo avoid backtracking, the complexity of the fast KMP algorithm is O (n+m)

KMP algorithm, a pattern matching algorithm proposed by Knuth,morris,pratt, is a very excellent pattern matching algorithm for any pattern and target sequence, which can complete matching search in linear time without degradation.

(1) The generation of partial matching tables:

First, understand two concepts: "prefix" and "suffix." "prefix" means the entire header combination of a string except the last character; "suffix" means all the tail combinations of a string except the first character.

A partial-match value is the length of the longest shared element of prefix and suffix. Take "Abcdabd" as an example: the prefix and suffix of "A" are all empty, the length of the total element is 0; "AB" has a prefix of [a], the suffix is [B], the length of the total element is 0; "ABC" is prefixed with [A, AB], the suffix is [BC, C], the length of the total element is 0; "ABCD" The prefix is [A, AB, ABC], and the suffix is [BCD, CD, D], the length of the total element is 0; "ABCDA" is prefixed with [A, AB, ABC, ABCD], suffix [bcda, CDA, DA, a], the total element is "A", the length is 1; "Abcdab" prefix For [A, AB, ABC, ABCD, ABCDA], the suffix is [Bcdab, Cdab, DAB, AB, B], the total element is "AB", the length is 2; "Abcdabd" prefix is [a, AB, ABC, ABCD, ABCDA, Abcdab], suffix is [Bcdabd, Cdabd, Dabd, ABD, BD, D], the length of the total element is 0.

moved digits = number of characters matched-corresponding partial match values

The previous six characters "Abcdab" are matched when a known space does not match d. The lookup table shows that the last matching character B corresponds to a "partial match" of 2, so the previous formula calculates the number of digits to move backwards: 6-2 = 4, so the search term is moved backwards by 4 digits.

The essence of "partial matching" is that sometimes there is a repetition of the head and tail of the string. For example, "Abcdab" has two "AB", then its "partial matching value" is 2 ("ab" length). When the search word moves, the first "AB" Moves backwards 4 bits (string length-a partial match) to the second "ab" position.

(2) Next array solution idea: that is, the partial matching table solution

Through the above can have a clear understanding of the principle of the KMP algorithm, then the next step is to achieve programming. One of the most important is how to find the length of the maximum same prefix for each bit based on the template string to be matched.

Rules:
(The symmetry below is not the center symmetry, but the central character at descriptor symmetry, such as not ABCCBA, but abcabc this symmetry.) When the first character of the current character is symmetric to 0, just compare the current character with that of the substring. This is very good understanding ah, the front are all 0, the description is asymmetrical, if added a character, to symmetrical words at most is the current and the first symmetry. For example agcta this inside T is 0, then the symmetry of the subsequent a is only to see if it is equal to the first character A. By this reasoning, we can sum up a rule, not only the front is 0, if the next value of the previous character is 1, then we compare the current character with the second character of the substring, because the preceding one is 1, which means that the preceding character is equal to the first, if this is equal to the second, It means that the symmetry level is 2. There are two characters symmetric. For example, above Agctag, the next of the second A is 1, which means that it is symmetric with the first a, and then we compare the last G to the second G, and then the natural symmetry values add up to 2. According to the above reasoning, if it has been equal, has been cumulative, you can always push ah, pushed here should not be a little difficult, if you find it difficult to say that I wrote too failed. Of course it's not going to go so well. Let us always symmetry, if we encounter the next inequality, then we can not inherit the previous symmetry, this situation can only explain not so much symmetry, but do not show that a little symmetry is not , so it is necessary to reconsider the situation, This is also the crux of the problem.

Combined with code understanding:

void Makenext (const char p[],int next[])
{
    int q,k;//q: template string subscript; k: maximum prefix length
    int m = strlen (P);//template string length
    Next[0] = The maximum prefix length of the first character of the 0;//template string is 0 for
    (q = 1,k = 0; q < m; ++q)//for loop, starting with the second character, and sequentially calculating the next value for each character
    {
        Whil E (k > 0 && p[q]!= p[k])//recursively find p[0] P[Q] The largest of the same prefix length k
            = next[k-1];//This while loop is the essence of the whole code, for example, try to help you understand.  
        if (p[q] = = P[k])//If equal, then the maximum same prefix length plus 1
        {
            k++;
        }
        NEXT[Q] = k;//Maximum prefix length is next value
    }
}

KMP Complete code:

#include <stdio.h> #include <string.h> void makenext (const char p[],int next[]) {int q,k;
    int m = strlen (P);
    Next[0] = 0;
        for (q = 1,k = 0; q < m. ++q) {while (k > 0 && p[q]!= p[k]) k = next[k-1];
        if (p[q] = = P[k]) {k++;
    } Next[q] = k;
    {Int. KMP (const char t[],const char p[],int next[]) {int n,m;
    int i,q;
    n = strlen (T);
    m = strlen (P);
    Makenext (P,next);
        for (i = 0,q = 0, i < n; ++i) {while (q > 0 && p[q]!= t[i]) q = next[q-1];
        if (p[q] = = T[i]) {q++;
        } if (q = = m) {printf ("pattern occurs with shift:%d\n", (i-m+1));
    int main () {int i;
    int next[20]={0};
    Char t[] = "ABABXBABABCADFDSSS";
    Char t[] = "Ababxbab abcdabd abcadfdsss";
    Char p[] = "ABCDABD";
    printf ("%s\n", T);
    printf ("%s\n", P); MAkenext (P,next);
    KMP (T,p,next);
    for (i = 0; i < strlen (P); ++i) {printf ("%d", next[i]);

    printf ("\ n");
return 0; }

Reference:
http://kb.cnblogs.com/page/176818/
http://www.cnblogs.com/10jschen/archive/2012/08/21/2648451.html

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.