String Matching Algorithm

Source: Internet
Author: User

There are many string matching algorithms, the most commonly used are KMP Algorithms and common algorithms.

1. common algorithms: this algorithm is the most efficient algorithm with the O (Nm) time complexity ).

The procedure is as follows:

bool str_match(const char * str1, const char * str2)//O(P*T){assert(str1 != NULL && str2 != NULL);int k = 0;for (unsigned int i = 0; i < strlen(str1); i ++){k = i;for (unsigned int j = 0; j < strlen(str2); j ++){if (*(str1 + k++) == *(str2 + j)){if (j == strlen(str2)-1)return true;}else break;}}return false;}


2. The KMP algorithm is an improved algorithm on a common algorithm. In a common algorithm, only one character is moved at a time in string P, while in the KMP algorithm, based on the method with the same suffix expression, you can skip a few characters and find the number of characters to move at the beginning of Algorithm Execution.

The procedure is as follows:

////---------------------------------------------------KMP-------------//void findNext(const char * strP, int * next){assert(strP != NULL && next != NULL);int lenP = strlen(strP);*next = -1;int i = 0;int j = -1;while (i < lenP){while (j == -1 || j < lenP && *(strP+i) == *(strP + j) ){j++;i++;if(*(strP+i) != *(strP + j))next[i] = j;elsenext[i] = next[j];}j = next[j];}}int KMP(const char * strP, const char *strT){assert(strP != NULL && strT != NULL);int lenP = strlen(strP);int * next = new int[lenP];findNext(strP,next);int i = 0;int j = 0;int lenT = strlen(strT);while (i <= strT-strP){while (j == -1 || j < lenP && *(strP+j) == *(strT + i)){i++;j++;}if (j == lenP){return i - lenP;}j = *(next+j);}delete [] next;return -1;}//--------------------------------------end of KMP-------------------------------------//




String Matching 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.