KMP算法实现

链接: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;
}

 

posted @ 2016-04-10 12:02  meadow@dlut  阅读(240)  评论(0编辑  收藏  举报