Several algorithms for string pattern matching

Source: Internet
Author: User

1. KMP algorithm

KMP algorithm program looks relatively simple, but the process of the next array is still difficult to understand, next array is the essence of the maximum prefix, the complexity of the algorithm is O (m+n), the algorithm flow is as follows:

    • Assuming that the text string s is now matched to the I position, the pattern string P matches to the J position
      • If j =-1, or if the current character matches successfully (ie s[i] = = P[j]), make i++,j++ continue to match the next character;
      • If J! =-1, and the current character match fails (that is, s[i]! = P[j]), then I is unchanged, j = next[j]. This means that when mismatch occurs, the pattern string p moves the J-next [j] bit to the right relative to the text string s.

For a detailed explanation look at this article http://blog.csdn.net/v_july_v/article/details/7041827

Find the code for the next array:

//an optimized next array methodvoidGetnextval (Char* p,intnext[]) {      intPlen =strlen (P); next[0] = -1; intK =-1; intj =0;  while(J < Plen-1)      {          //P[k] Represents a prefix, p[j] represents a suffix        if(k = =-1|| P[J] = =P[k]) {              ++J; ++K; //The main purpose here is to prevent two matches from failing .            if(P[j]! =P[k]) next[j]= k;Else                  //because the p[j] = p[Next[j]] is not present, so you need to continue recursion when it appears, k = next[k] = next[next[k]]NEXT[J] =Next[k]; }          Else{k=Next[k]; }      }  

The KMP code is very similar to the code for the next array:

intKmpsearch (Char* S,Char*p) {inti =0; intj =0; intSlen =strlen (s); intPlen =strlen (P);  while(I < Slen && J <Plen) {          //① If J =-1, or if the current character match succeeds (ie s[i] = = P[j]), the i++,j++        if(j = =-1|| S[i] = =P[j]) {i++; J++; }          Else          {              //② If J! =-1, and the current character match fails (that is, s[i]! = P[j]), then I is unchanged, j = Next[j]//Next[j] is the next value corresponding to Jj =Next[j]; }      }      if(J = =Plen)returnIJ; Else          return-1; }  

2. BM algorithm

BM algorithm is from the back to the beginning of the comparison, the algorithm mainly used in two preprocessing array bad symbol and good suffix mobile table, in each match failure, from the two tables to select the largest value of the next match start position, detailed introduction can refer to this article HTTP/ blog.csdn.net/eric491179912/article/details/6210009

Code:

voidPREBMBC (Char*x,intMintbmbc[]) {       inti;  for(i =0; i < asize; ++i) bmbc[i]=m;  for(i =0; I < M-1; ++i) bmbc[x[i]= M-i-1; }    voidSuffixes (Char*x,intMint*Suff) {       intF, G, I; F=0; Suff[m-1] =m; G= M-1;  for(i = m-2; I >=0; --i) {if(I > G && suff[i + M-1-F] < I-g) Suff[i]= Suff[i + M-1-F]; Else {             if(I <g) G=i; F=i;  while(g >=0&& X[g] = = x[g + M-1-F])--G; Suff[i]= f-G; }       }    }    voidPrebmgs (Char*x,intMintbmgs[]) {       intI, J, Suff[xsize];       Suffixes (x, M, Suff);  for(i =0; I < m; ++i) bmgs[i]=m; J=0;  for(i = m-1; I >=0; --i)if(Suff[i] = = i +1)              for(; J < M-1I ++j)if(Bmgs[j] = =m) Bmgs[j]= M-1-i;  for(i =0; I <= M-2; ++i) bmgs[m-1-Suff[i]] = m-1-i; }    voidEMOChar*x,intMChar(ynintN) {intI, J, Bmgs[xsize], bmbc[asize]; /*preprocessing*/Prebmgs (x, M, Bmgs);       PREBMBC (x, M, BMBC); /*Searching*/J=0;  while(J <= N-m) { for(i = m-1; I >=0&& X[i] = = Y[i + j]; --i); if(I <0) {OUTPUT (j); J+ = bmgs[0]; }          ElseJ+ = MAX (Bmgs[i], Bmbc[y[i + j])-M +1+i); }    }  

3. Horspool algorithm
Horspool is a simplified version of the BM algorithm, the algorithm is not only simple, but also in the processing of random strings, the efficiency is not necessarily lower than the BM algorithm. The worst efficiency of the algorithm is O (MN), but for random text, its efficiency belongs to O (n), the main process of the algorithm:

(1) Construction transfer table

T (c) = length of pattern m (if C is not contained in m-1 characters)

= the distance from right to left for the first occurrence of C (in other cases)

(2) Align the pattern with the beginning of the text

(3) Repeat the following procedure, knowing that a matching substring or pattern has reached the last character of the text. Starting with the last character in the pattern, compare the pattern and the corresponding characters in the text, knowing that either all M characters match or a mismatched character is encountered.

In the latter case, if C is a character that is relative to the last character in the current text and the pattern, move the pattern to the right of the T (c) character along the text.

Code:

voidShittable (Char*p,intPlen,int*table,inttable_size) {     for(intI=0; i<table_size;i++)//Initialize the transfer table to Plen Table[i]=Plen;  for(intI=0; i<plen-2; i++) Table[p[i]]=plen-1-i;}intHorspoolmatching (Char*p,intPlen,Char*t,intTlen,int*Table)    {shittable (p,plen,table); inti=plen-1;//the right-most position of the pattern     while(i<=tlen-1)    {        intk=0;//number of matching characters         while(k<=plen-1&& p[plen-1-K] = = t[i-K]) K++; if(k==Plen)returni-plen+1; ElseI=i+Table[t[i]]; }    return-1;}

4. Sunday algorithm

The idea of the Sunday algorithm is very similar to the bad character thought in the BM algorithm.

The difference is that the Sunday algorithm after the mismatch, is to take the target string in the current and pattern string corresponding to the next position of the characters to do bad character matching. such as: Subscript number: 01234567890 target string: Abcdefghijk mode string: Bxcd BM Algorithm after B and X mismatch, the bad character is B (subscript 1), in the pattern string to find the position of B, after the corresponding, moved to the following position to continue matching. Target string: Abcdefghijk mode string: Bxcd and in the Sunday algorithm, for the above match, found mismatch, is taken in the target string and the corresponding part of the pattern string after a character, that is, E, and then use E to do bad character matching. E is not in the pattern string, so using the Sunday algorithm, next move to the following position to continue the match. Target string: Abcdefghijk mode string: Bxcd From here it can be seen that the Sunday algorithm than the BM algorithm displacement is greater, so the Sunday algorithm than the BM algorithm efficiency is higher. But the worst time complexity still has O (target string length * pattern string length). Consider such a target string: baaaabaaaabaaaabaaaa, to search for aaaaa inside, obviously there is no matching position. However, if the Sunday algorithm is used, most of the bad characters are a, and the pattern string is all a, so in most cases, the pattern string can only move 1 bits to the right when the mismatch is found. If the improved KMP algorithm is used, it is still possible to ensure that the linear time is matched. In addition, using the Sunday algorithm does not require a fixed left-to-right match or a right-to-left match (this is because after the mismatch we use the last character in the target string), we can calculate the probability of the occurrence of the characters in the pattern string in advance, Each time you use the lowest probability of the character's location to compare, so the probability of mismatch is relatively large, so you can reduce the number of comparisons, speed up the matching speed. As in the following example: Target string: Abcdefghijk mode string: AABCC pattern string B only appeared once, A,c all appeared 2 times, so we can first compare the position of B (only see the characters in the pattern string, b mismatch probability will be relatively large). In short, the Sunday algorithm is simple to understand, thinking out of the conventional matching idea, in terms of probability, its efficiency in matching random strings than other matching algorithm is faster.
BOOLBadchar (Const Char*pattern,intNlen,int*parray,intNarraylen) {      if(Narraylen < the)      {          return false; }       for(inti =0; I < the; i++) {Parray[i]= -1; }       for(inti =0; i < Nlen; i++) {Parray[pattern[i]]=i; }      return true; }    intSundaysearch (Const Char*dest,intNdlen,Const Char*pattern,intNplen,int*Parray) {      if(0==Nplen) {          return-1; }       for(intNbegin =0; Nbegin <= ndlen-Nplen;) {          inti = nbegin, j =0;  for(; J < Nplen && i < Ndlen && Dest[i] = = pattern[j];i++, j + +); if(J = =Nplen) {              returnNbegin; }          if(Nbegin + Nplen >Ndlen) {              return-1; }          Else{Nbegin+ = nplen-parray[dest[nbegin+Nplen]]; }      }      return-1; }    

Several algorithms for string pattern matching

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.