本文参考阮一峰老师的KMP算法,重点是“部分匹配表”的建立。算法可参考 http://kb.cnblogs.com/page/176818/ 。
/* * kmp.cpp * Author: Qiang Xiao * Time: 2015-07-18 */ #include<iostream> #include<string> using namespace std; int kmp(string& ma, string& sub, int a[]); int max_fix_len(string& a, int len); int main(){ string ma= "ABCCBB"; string sub= "CCB"; int dis[sub.length()]; dis[0]= -1; for(int i= 1; i< sub.length(); i++){ dis[i]= max_fix_len(sub, i+1); } int km= kmp(ma, sub, dis); cout<<ma<<endl<<sub<<endl; cout<<km<<endl; return 0; } int max_fix_len(string& a, int len){ int ll= 1; //ll denotes the length of prefix, perspectively. int maxLen= 0; while(ll< len){ int j; for(j= 0; j< ll; j++){ if(a.at(j)!= a.at(len+j-ll)) break; } if(j== ll- 1) maxLen= ll- 1; ll++; } return maxLen; } int kmp(string& ma, string& sub, int dis[]){ int lens= sub.length(); int lenm= ma.length(); int wai= 0; while(wai< lenm- lens){ int nei1= 0; //sub int nei2= wai; //ma for(nei1= 0; nei1< lens; nei1++){ if(ma.at(nei2)== sub.at(nei1)){ nei1++; nei2++; } else{ nei1++; break; } } if(nei1== lens){ return wai+ 1; } wai= wai+ nei1- dis[nei1- 1]- 1; } return -1; }
运行结果为:
xiaoq@xq-ubun:~/C/DataStructure$ g++ kmp.cpp -o kmp.o xiaoq@xq-ubun:~/C/DataStructure$ ./kmp.o ABCCBB CCB 3 xiaoq@xq-ubun:~/C/DataStructure$
如果错误,请指正。
欢迎交流!