KMP演算法的一個C++實現

來源:互聯網
上載者:User

標籤:

本文參考阮一峰老師的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;}

運行結果為:

[email protected]:~/C/DataStructure$ g++ kmp.cpp -o kmp.o[email protected]-ubun:~/C/DataStructure$ ./kmp.o ABCCBBCCB3[email protected]-ubun:~/C/DataStructure$

如果錯誤,請指正。

歡迎交流!

KMP演算法的一個C++實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.