KMP算法

来源:互联网 发布:王宇直 知乎 编辑:程序博客网 时间:2024/06/04 20:01

NOI前复习模板——KMP算法


hihocoder 模板题

多组询问,求模式串在匹配串中的出现次数。


C++模板

#include <cstdio>#include <cstring>int testCases;const int maxLength = 1000005;char sub[maxLength]; int lenOfSub;char str[maxLength]; int lenOfStr;int next[maxLength];signed main() {scanf("%d", &testCases);for (int cas = 1; cas <= testCases; ++cas) {// read two strings from inputscanf("%s", sub), lenOfSub = strlen(sub);scanf("%s", str), lenOfStr = strlen(str);// get the next array for substringnext[0] = -1;for (int i = 0, j = -1; i < lenOfSub; )if (j == -1 || sub[i] == sub[j])next[++i] = ++j;elsej = next[j];// count with the help of next[]int answer = 0;for (int i = 0, j = 0; i < lenOfStr; ) {if (j == -1 || str[i] == sub[j])++i, ++j;elsej = next[j];if (j == lenOfSub)++answer, j = next[j];}// write the answerprintf("%d\n", answer);}}