Here is the code: BM is what reference Nanyi Teacher's explanation click Open link
#include <iostream> #include <algorithm> #include <string.h> #include <string> #include < stdio.h> #include <stdlib.h> #include <math.h> #include <vector> #include <time.h> #include <windows.h>using namespace Std;const int max_size=5005;void set_asc (int *asc,int len,string& b,int& last) {int i; for (i=0; i<len; i++) {asc[(int) b[i]]=i; if (b[i]==b[len-1]&&i!=len-1) last=i; }}int BM (String &a,string& b) {int asc[260],lena=a.size (), lenb=b.size (); int i=lenb-1,j=lenb-1; int last=-1; memset (asc,-1,sizeof (ASC)); SET_ASC (Asc,lenb,b,last); while (I<LENA&&J<LENB) {int ii,jj; Ii=i,jj=j; while (1) {if (A[ii]==b[jj]) {if (jj==0) return ii+1; II--, jj--; } else {if (jj!=lenb-1) I+=max ((jj-asc[(int) a[ii]]), lenb-1-last); else i+= (jj-asc[(int) a[ii]]); J=lenb-1; Break }}} return-1;} void Set_kmp_next (int *kmp_next,int len,string& b) {int i=0,j=-1; Kmp_next[0]=-1; while (I<len) {if (j==-1| | B[i]==b[j]) {i++; j + +; Kmp_next[i]=j; } else j=kmp_next[j]; }}int KMP (string &a,string& B)//A is the original string, B is the pattern string {int i,j,lena=a.size (), lenb=b.size (); int kmp_next[max_size]; Set_kmp_next (KMP_NEXT,LENB,B); i=j=0; while (I<lena) {if (j==-1| | A[i]==b[j]) {i++; j + +; } else j=kmp_next[j]; if (J==LENB) return i-j+1; } return-1;} int main () {//Freopen ("Stdin.txt", "R", stdin);//Freopen ("Stdout.txt", "w", stdout); String A, B; while (cin>>a>>b) {printf ("%d\n", BM (A, b)); printf ("%d\n", KMP (A, b)); printf ("\ n"); } return 0;}
BM algorithm pattern Matching--comparison between string and KMP