题目连接:https://vjudge.net/contest/70325#problem/C
题目:
abcde a3 aaaaaa aa #Sample Output
0 3
思路:求不覆盖的kmp,只要把当j==模式串长度时,后面的j==0即可,这样又重新开始从0开始,一满足长度为模式串时,ans就加一
// // Created by HJYL on 2019/8/15. // #include <iostream> #include <vector> #include <map> #include <string> #include <queue> #include <stack> #include <set> #include <algorithm> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> using namespace std; typedef long long ll; const int maxn=1e6+10; char str[maxn],str1[maxn]; int nextt[maxn]; void getnext() { int i=0,j=-1; int n=strlen(str1); nextt[0]=-1; while(i<n) { if(j==-1||str1[i]==str1[j]) { ++i,++j; if(str1[i]!=str1[j]) nextt[i]=j; else nextt[i]=nextt[j]; } else j=nextt[j]; } } int kmp() { int i=0,j=0; int ans=0; int m=strlen(str); int n=strlen(str1); while(i<m) { if(j==-1||str[i]==str1[j]) { i++,j++; } else j=nextt[j]; if(j==n) j=0,ans++; } return ans; } int main() { while(~scanf("%s",str)) { if(str[0]==‘#‘) break; scanf("%s",str1); getnext(); printf("%d\n",kmp()); } return 0; }
[kuangbin带你飞]专题十六 KMP & 扩展KMP & ManacherC - 剪花布条 HDU - 2087 (kmp不覆盖匹配)
原文:https://www.cnblogs.com/Vampire6/p/11357352.html