Learning string matching algorithm for some time, but still a little confused, although the understanding of the algorithm process, but in the coding time will be a little confused.
First put the written program here, and then have time to turn to look at it!
#include <iostream> #include <string>using namespace Std;int kmpfind (char* S, char* p); void GetNext (char* p, int next[]); int Violentmatch (char* s, char* p); int main () {char s1[] = "Abcaabbaacaadaabbaa"; char s2[] = "Aadaab"; cout < < "in the string" << S1 << ", the string" << S2 << "was started at the" << Violentmatch (S1, S2); cout << endl<<kmpfind (S1, S2) <<endl;return 0;} void GetNext (char* p, int next[]) {int plen = strlen (p); int i =-1; int j = 0;//i starting from 1, matching the mismatch back to the starting position next[0] = -1;//for ( ; J < pLen-1;) {if (i==-1| | P[i] = = P[j]) {++i; ++j; next[j] = i;} Elsei = next[i];//i backtracking to Next[i]}}int Kmpfind (char* S, char* p) {int i = 0;int J = 0;int Slen = strlen (s); int plen = strlen (p); int * next = new Int[strlen (p)]; GetNext (P, next), 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] That is, by the next array to get the position j = Next[j];}} Delete []next;if (j = = Plen)//compare complete and compare the length of the pattern string to find a matching string return i-j;elsereturn-1;} int Violentmatch (char* s, char* p) {int slen = strlen (s); int plen = strlen (p); int i = 0;int j = 0;while (i < Slen && Amp J < Plen) {if (s[i] = = P[j]) {//① If the current character matches successfully (i.e. s[i] = = P[j]), then i++,j++ i++;j++;} Else{//② if mismatch (i.e. s[i]! = P[j]), let i = i-(j-1), j = 0 i = i-j + 1;j = 0;}} The match succeeds, returns the position of the pattern string p in the text string s, otherwise returns-1 if (j = = Plen) return i-j;elsereturn-1;}
Algorithm for string matching (brute force algorithm and KMP algorithm)