String Matching Algorithm-based KMP Algorithm

Source: Internet
Author: User

This algorithm is a leader in the string matching algorithm. It only uses the time of O (lengthText + lengthPattern) to complete the matching task. The reason for his speed is that there is no need to trace back. The most profound and difficult part of this algorithm is that the two strings are matched, and the success or failure is only related to the template string and the target string. If the template string fails to match in the j position, you do not need to re-enter the 0 position. The next position should be next [j. The following is the function for generating the next array: [cpp] void GetNext (string Pattern, vector <int> & next) {int j = 0; int k =-1; int lenP = Pattern. length (); next. assign (8,-1); while (j <lenP) {if (k =-1) | (Pattern [j] = Pattern [k]) {j ++; k ++; next [j] = k;} else {k = next [k] ;}} below is the KMP algorithm: [cpp] int KMP (string Text, string Pattern, vector <int> & next, int TdefPos = 0) {int posP = 0, posT = TdefPos; int lenP = Pattern. length (); int lenT = Text. length (); while (posP <lenP) & (posT <lenT) {if (posP =-1) | Pattern [posP] = Text [posT]) {posP ++; posT ++;} else {posP = next [posP] ;}} if (posP <lenP) {return-1;} else {return (lenT-lenP );}}

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.