HDU 1686:Oulipo(KMP入门)

来源:互联网 发布:詹姆斯场均数据 编辑:程序博客网 时间:2024/06/08 19:35

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1686



题目翻译:给出一个模式串,给出一个文本串,求模式串在文本串中出现

了多少次?


解题思路:KMP入门


AC代码:

#include <iostream>#include <stdio.h>#include <string.h>using namespace std;char text[1000010];char patten[10010];int nex[10010];void getNext() {    int len = strlen(patten);    nex[0] = -1;    int k = -1,j = 0;    while(j < len) {        if(k == -1 || patten[j]==patten[k]) {            k++;            j++;            nex[j] = k;        }        else {            k = nex[k];        }    }}int kmp() {    int i = 0,j = 0,ans=0;    int lenp = strlen(patten);   ///模式串的长度    int lent = strlen(text);   ///文本串的查改都    while(i < lent) {        if(j == -1 || text[i]==patten[j]) {            i++;            j++;        }        else            j = nex[j];        if(j == lenp) {            ans++;        }    }    return ans;}int main() {    int T;    scanf("%d",&T);   ///T组测试数据    while(T--) {        scanf("%s",patten);        scanf("%s",text);        getNext();        int ans = kmp();        printf("%d\n",ans);    }    return 0;}