KMP 模板

int* findNext(string& s) {
    int len = s.length();
    int* next = new int[len];
    next[0] = -1;
    int i, k;
    i = 0, k = -1;
    while (i < len - 1) {
        while (k >= 0 && s[i] != s[k])
            k = next[k];
        i++;
        k++;
        next[i] = k;
    }
    return next;
};
int* findBetterNext(string& s) {
    int len = s.length();
    int* next = new int[len];
    next[0] = -1;
    int i, k;
    i = 0, k = -1;
    while (i < len - 1) {
        while (k >= 0 && s[i] != s[k])
            k = next[k];
        i++;
        k++;
        if (s[i] == s[k]) {
            next[i] = next[k];
        }
        else next[i] = k;
    }
    return next;
}
int kmpStringMatch(string& s, string& p) {
    int i = 0, j = 0;
    int slen = s.length(), plen = p.length();
    int* next = findBetterNext(s);
    while (j < plen&&i < slen) {
        if (j == -1 || s[i] == p[j]) {
            if (j != -1)
            i++;
            j++;
        }
        else {
            j = next[j];
        }
    }
    if (j == plen)
        return i - plen;
    else
        return -1;
}

你可能感兴趣的:(KMP 模板)