KMP字符串匹配模板

首先给出KMP模板:

#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
using namespace std;
const int maxn = 1e4+7;

char text[maxn*100], pat[maxn];
int lent, lenp, nextp[maxn];

void get_next() {
    int i, j = -1;
    nextp[0] = -1;
    for(i = 1; i <= lenp;i++) {
        while(j > -1&&pat[j+1] != pat[i]) j = nextp[j];
        if(pat[j + 1] == pat[i]) j++;
        nextp[i] = j;
    }
}

int KMP() {
    int ans = 0, i = 0, j = -1;
    get_next();
    for(i = 0; i < lent; i++) {
        while(j != -1&&pat[j+1] != text[i]) {
            j = nextp[j];
        }
        if(pat[j+1] == text[i]) j = j + 1;
        if(j == lenp - 1) ans++;
    }
    return ans;          //返回匹配串的个数;
}


int main()
{
    int t;
    scanf("%d", &t);
    while(t--) {
        scanf("%s%s", pat, text);
        lent = strlen(text);
        lenp = strlen(pat);
        printf("%d\n", KMP());
    }
    return 0;
}

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/weixin_39792252/article/details/80003905
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞