字符串匹配——KMP算法

#include <cstdio>
#include <cstring>

const int N = 1000000 + 5;
char s[N],t[N];
int lens,lent;

int next[N];

void get_fail() {
    next[0] = -1;
    for (int i = 1,j = -1; i < lent; ++ i) {
        while (j != -1 && t[i] != t[j+1]) j = next[j];
        next[i] = t[i] == t[j+1] ? ++ j : j ;
    }
}

int work() {
    lens = strlen(s);
    lent = strlen(t);
    get_fail();
    int ret = 0;
    for (int i = 0,j = -1; i < lens; ++ i) {
        while (j != -1 && s[i] != t[j+1]) j = next[j];
        if (s[i] == t[j+1]) {
            ++ j;
            if (j == lent-1) {
                j = -1;
                ret ++;
            }
        }
    }
    return ret;
}

int main() {
   // freopen ("a.txt" , "r" , stdin ) ;
    while (scanf("%s",s) != EOF) {
        scanf("%s",t);
        printf("%d\n",work());
    }
    return 0;
}
View Code

 

posted @ 2015-04-14 21:44  Painting、时光  阅读(115)  评论(0编辑  收藏  举报