#include"stdio.h" #include"string.h" #define M 4444 int next[M],ans; void getNext(char *b) { int i,j; i=0; j=-1; next[0]=-1; while(b[i]!=' ') { if(j==-1||b[i]==b[j]) { i++; j++; next[i]=j; } else j=next[j]; } } void KMP(char *a,char *b) { int i,j; i=j=0; int m=strlen(b); while(a[i]!=' ') { if(j==-1||a[i]==b[j]) { i++; j++; } else j=next[j]; if(j==m) { ans++; j=next[j]; } } } int main() { char ch[M],str[M]; while(scanf("%s",str),strcmp(str,"#")!=0) { scanf("%s",ch); getNext(ch); ans=0; KMP(str,ch); printf("%d ",ans); } }
aaaa aa
#
3
#include"stdio.h" #include"string.h" #define M 4444 int next[M],ans; void getNext(char *b) { int i,j; i=0; j=-1; next[0]=-1; while(b[i]!=' ') { if(j==-1||b[i]==b[j]) { i++; j++; next[i]=j; } else j=next[j]; } } void KMP(char *a,char *b) { int i,j; i=j=0; int m=strlen(b); while(a[i]!=' ') { if(j==-1||a[i]==b[j]) { i++; j++; } else j=next[j]; if(j==m) { ans++; j=next[j]+m;//区别 } } } int main() { char ch[M],str[M]; while(scanf("%s",str),strcmp(str,"#")!=0) { scanf("%s",ch); getNext(ch); ans=0; KMP(str,ch); printf("%d ",ans); } }
aaaaa aa
#
2