POJ

来源:互联网 发布:怎么用ipad看淘宝直播 编辑:程序博客网 时间:2024/06/15 07:31

求模式串在字符串中出现的次数。

统计次数时,要注意当完成一组匹配之后令j = next【j】,以便开启另一组匹配

#include <cstdio>#include <cstring>#include <iostream>using namespace std;const int maxn = 1000000 + 10;int next[maxn], leno, lenp;char o[maxn], p[maxn];void NEXT() {    int i = 0, j = -1;    next[0] = -1;    while (i < lenp) {        if (j == -1 || p[i] == p[j]) {            i++, j++;            if (p[i] != p[j]) next[i] = j;            else next[i] = next[j];        }        else j = next[j];    }}void KMP() {    int i = 0, j = 0, cnt = 0;    while (i < leno && j < lenp) {        if (j == -1 || o[i] == p[j]) {            i++, j++;        }        else j = next[j];        if (j == lenp) {            j = next[j], cnt++;        }    }    printf("%d\n", cnt);}int main() {    int T; scanf("%d", &T);    while (T--) {        scanf("%s%s", p, o);        leno = strlen(o), lenp = strlen(p);        NEXT();        KMP();    }    return 0;}


原创粉丝点击