A C + + implementation of KMP algorithm

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.