This paper refers to Nanyi Teacher's KMP algorithm, focusing on the establishment of "partial matching table". The algorithm can refer to http://kb.cnblogs.com/page/176818/.
/** kmp.cpp* Author:qiang xiao* time:2015-07-18*/#include<iostream>#include<string>using namespacestd;intKmpstring& MA,string& Sub,inta[]); intMax_fix_len (string& A,intLen); intMain () {stringMa="ABCCBB"; stringsub="CCB"; intdis[sub.length ()]; dis[0]= -1; for(intI=1; i< sub.length (); i++) {Dis[i]= Max_fix_len (Sub, i+1); } intkm=KMP (MA, Sub, dis); cout<<ma<<endl<<sub<<Endl; cout<<km<<Endl; return 0;}intMax_fix_len (string& A,intLen) { intLl=1;//ll denotes the length of prefix, perspectively. intmaxlen=0; while(ll<Len) { intJ; for(j=0; j< ll; J + +){ if(a.at (j)! = a.at (len+j-ll)) Break; } if(j== ll-1) MaxLen= ll-1; ll++; } returnMaxLen;}intKmpstring& MA,string& Sub,intdis[]) { intlens=sub.length (); intlenm=ma.length (); intWai=0; while(wai< lenm-lens) { intnei1=0;//Sub intNei2= Wai;//Ma for(nei1=0; nei1< Lens; nei1++){ if(ma.at (nei2) = =sub.at (NEI1)) {Nei1++; Nei2++; } Else{nei1++; Break; } } if(nei1==lens) { returnwai+1; } Wai= wai+ nei1-dis[nei1-1]-1; } return-1;}
The result of the operation is:
[Email protected]:~/c/datastructure$ g++ kmp.cpp-o kmp.o[email protected]-ubun:~/c/datastructure$. KMP.O ABCCBBCCB3[email protected]-ubun:~/c/datastructure$
If it is wrong, please correct me.
Welcome to the Exchange!
A C + + implementation of KMP algorithm