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