首页 > 代码库 > KMP 模板

KMP 模板

 模板-KMP

#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
namespace _kmp {
    #define foreach(i, l, r) for(int i = (l); i < (r); ++i)
    typedef vector < pair<int, int> > AA;
    const int N = 100000 + 5;
    int next[N];
    void init(const char *obj, int lo) {
        next[0] = -1;
        int j = -1;       //represent can match [0, j] at most.
        foreach(i, 1, lo) {
            while(j != -1 && obj[j + 1] != obj[i]) {    
                j = next[j];
            }
            if(obj[j + 1] == obj[i]) {
                next[i] = ++j;
            }
            else {
                next[i] = j;
            }
        }
    }
   AA match(const char *me, int lm, const char *obj, int lo) {
        AA ret;
        int j = -1;       //represent can match [0, j] at most.
        foreach(i, 0, lm) {
            while(j != -1 && obj[j + 1] != me[i]) {
                j = next[j];
            }
            if(obj[j + 1] == me[i]) {
                if(++j == lo - 1) {
                    ret.push_back(make_pair(i - j, i));
                }
            }
        }
        return ret;
    }
    #undef foreach(i, l, r)
}

int main() {
    char me[] = "abababaababa";
    char obj[] = "aba";
     _kmp::init(obj, strlen(obj));
     _kmp::AA ret = _kmp::match(me, strlen(me), obj, strlen(obj));
    for(int i = 0; i < (int)ret.size(); ++i) {
        printf("{%d,%d}\n", ret[i].first, ret[i].second);
    }
    return 0;
}


KMP 模板