String processing: The Brooks--FOSS algorithm

Source: Internet
Author: User

Basic idea:

The basic idea is to compare the first character of the main string with the first characters of the pattern string, and if it is equal, continue the subsequent comparison of the characters character, otherwise the second character of the main string character with the first characters of the pattern string until each character in the pattern string is equal to a sequential sequence of characters in the main string. This is known as a match success, otherwise it is called a match failure.

A simple pattern matching algorithm is implemented by storing strings in a character array.

1 intIndex (CharS[],CharT[],intPOS)2 /*finds and returns the position of the pattern string T in the main string s starting from the POS (subscript), or 1 if T is not a substring of s*/3 {4i = pos; j=0;//I, J is used to indicate the position of the main string character and the pattern string character (subscript) respectively5Slen = strlen (S); Tlen = strlen (T);//calculate the length of the main string and the pattern string6      while(I < Slen && J <Tlen)7     {8         if(S[i] = =T[j])9         {Teni++;j++; One         } A         Else -         { -i = I-j +1;//position pointer fallback for main string character thej =0; -          } -     } -     if(J >= Tlen)//Match Success +         returnITlen; -     return-1;//match failed, return-1 +}
Complexity of Time:

In the best case, the time complexity of the matching algorithm is O (n + M). In the worst case, the time complexity is O (NXM), the improved pattern matching algorithm is also called the KMP algorithm, the improvement is: each time the matching process occurs when the comparison of the characters are not equal, Position pointers that do not need to retrace the main string characters. Instead, use the result of the "partial match" that has been obtained to "slide" the pattern string backwards as far as possible before continuing the comparison.

String processing: The Brooks--FOSS algorithm

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.