abcde a3 aaaaaa aa #
0 3
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <string> #include <map> #include <stack> #include <vector> #include <set> #include <queue> #pragma comment (linker,"/STACK:102400000,102400000") #define maxn 1005 #define MAXN 2005 #define mod 1000000009 #define INF 0x3f3f3f3f #define pi acos(-1.0) #define eps 1e-6 typedef long long ll; using namespace std; char str[maxn],pstr[maxn]; int nextval[maxn]; void get_nextval() { int plen=strlen(pstr+1); int i=1,j=0; while (i<plen) { if (j==0||pstr[i]==pstr[j]) { i++; j++; if (pstr[i]!=pstr[j]) nextval[i]=j; else nextval[i]=nextval[j]; } else j=nextval[j]; } for (int i=1;i<=plen;i++) printf("%d ",nextval[i]); printf("\n"); } int KMP() { int plen=strlen(pstr+1); int len=strlen(str+1); int i=0,j=0,ans=0; while (i<=len) { if (j==0||str[i]==pstr[j]) { if (j>=plen) { ans++; j=0; } i++; j++; } else j=nextval[j]; } return ans; } int main() { while (scanf("%s",str+1)) { if (str[1]=='#') break; scanf("%s",pstr+1); get_nextval(); printf("%d\n",KMP()); } return 0; }
原文地址:http://blog.csdn.net/u014422052/article/details/40212873