现在的位置: 首页 > 综合 > 正文

模版 – KMP

2018年04月04日 ⁄ 综合 ⁄ 共 928字 ⁄ 字号 评论关闭

#include <vector>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

namespace __xiaod_kmp {
    #define foreach(i, l, r) for(int i = (l); i < (r); ++i)
    typedef vector < pair<int, int> > VPII;
    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]) {    //find the better choose.
                j = next[j];
            }
            if(obj[j + 1] == obj[i]) {
                next[i] = ++j;
            }
            else {
                next[i] = j;
            }
        }
    }
    VPII match(const char *me, int lm, const char *obj, int lo) {
        VPII 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";
    __xiaod_kmp::init(obj, strlen(obj));
    __xiaod_kmp::VPII ret = __xiaod_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;
}

抱歉!评论已关闭.