KMP演算法實現

來源:互聯網
上載者:User

標籤:

連結:http://blog.csdn.net/joylnwang/article/details/6778316

KMP演算法是一種很經典的字串匹配演算法,連結中的講解已經是很明確得了,自己按照其講解大體實現了一遍,感覺還不錯。其演算法的效率在於next表的建立上,宗旨就是避免樸素匹配演算法中的冗餘回溯問題。還是直接上代碼吧。

#ifndef ALGKMP_H__#define ALGKMP_H__static class KMP{public:    KMP(char *pattern, char *target, int &index);    ~KMP();private:    int patternLen;    int *next;    void calNextTable(char *pattern);};KMP::KMP(char *pattern, char *target, int &index){    patternLen = strlen(pattern);    next = new int[patternLen];    calNextTable(pattern);    index = 0;    while(index < strlen(target) - patternLen)    {        int flag = 0;        for (; flag < patternLen; flag++)        {            if (pattern[flag] != target[index + flag])            {                index = index+1 + flag - next[flag];                break;            }        }        if (flag == patternLen)break;    }    if (index == strlen(target) - patternLen)index = -1;}KMP::~KMP(){    delete[] next;}void KMP::calNextTable(char *pattern){    //int *f = new int[patternLen];    //f[0] = 0;    next[0] = 0;    /*--------------待最佳化----------------------*/    for (int i = 1; i < patternLen; i++)    {        int value = 0;        for (int k = 0; k < i - 1; k++)        {            int flag = 0;            for (flag = 0; flag <= k; flag++)            {                if (pattern[flag] != pattern[i - 1 - k + flag])break;            }            if (flag == k + 1)value = k + 1;        }        next[i] = value + 1;        for (int j = 0; j < i; j++)        {            if (pattern[i] == pattern[j])            {                next[i] = next[j];                break;            }        }    }    //delete f;}#endif

demo:

#include"iostream"#include"AlgKMP.h"using namespace std;int main(int argv, char *argc[]){  int index;  KMP("BBBC", "BBBBCDEFG", index);  cout <<index<< endl; 
return 0;
}

 

KMP演算法實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.