BM,KMP算法

Boyer-Moore
KMP

#include
#include
#include
#include
#include
#include
#include
#include
#include 
#include
using namespace std;
const int maxn = 5005;
int lena, lenb;
string a, b;
void set_ASC(int* ASC, int len, string& b, int& last) {
     
    for (int i = 0; i < len; i++) {
     
        ASC[(int)b[i]] = i;
        if (b[i] == b[len - 1] && i != len - 1) last = i;
    }
}
int bm() {
     
    int ASC[260];
    int i = lenb - 1, j = lenb - 1;
    int last = -1;
    memset(ASC, -1, sizeof(ASC));
    set_ASC(ASC, lenb, b, last);
    while (i < lena && j < lenb) {
     
        int ii = i, jj = j;
        while (1) {
     
            if (a[ii] == b[jj]) {
     
                if (jj == 0) return ii + 1;
                ii--, jj--;
            }
            else {
     
                if (jj != lenb - 1) i += max((jj - ASC[(int)a[ii]]), lenb - 1 - last);
                else i += (jj - ASC[(int)a[ii]]);
                j = lenb - 1;
                break;
            }
        }
    }
    return -1;
}
void set_kmp_next(int* kmp_next, int len) {
     
    int i = 0, j = -1;
    kmp_next[0] = -1;
    while (i < len) {
     
        if (j == -1 || b[i] == b[j]) {
     
            i++; j++;
            kmp_next[i] = j;
        }
        else j = kmp_next[j];
    }
}
int kmp() {
     
    int i, j, kmp_next[maxn];
    set_kmp_next(kmp_next, lenb);
    i = j = 0;
    while (i < lena) {
     
        if (j == -1 || a[i] == b[j]) {
     
            i++; j++;
        }
        else j = kmp_next[j];
        if (j == lenb) return i - j + 1;
    }
    return -1;
}
int main() {
     
    while (cin >> a >> b) {
     
        lena = a.size(); lenb = b.size();
        printf("%d\n", bm());
        printf("%d\n", kmp());
        printf("\n");
        a.clear(); b.clear();
    }
    return 0;
}

你可能感兴趣的:(BM,KMP算法)