标签:
Time Limit: 1000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
Description
Input
Output
Sample Input
abcde a3
aaaaaa aa
#
Sample Output
0
3
Source
kmp匹配相同串,贪心截取。
1 /**/ 2 #include<iostream> 3 #include<cstdio> 4 #include<cmath> 5 #include<cstring> 6 #include<algorithm> 7 using namespace std; 8 const int mxn=1020; 9 char s[mxn],c[mxn]; 10 int next[mxn],w[mxn]; 11 int la,lb; 12 void KMP(){ 13 next[0]=-1; 14 int i,j; 15 j=-1; 16 for(i=1;i<lb;i++){ 17 while(j>=0 && c[j]!=c[i])j=next[j]; 18 if(c[j+1]==c[i])j++; 19 next[i]=j; 20 } 21 j=0; 22 for(i=1;i<la;i++){ 23 while(j>=0 && s[i]!=c[j+1])j=next[j]; 24 if(c[j+1]==s[i])j++; 25 w[i]=j; 26 } 27 } 28 int main(){ 29 while(scanf("%s",s) && s[0]!=‘#‘){ 30 scanf("%s",c); 31 la=strlen(s); 32 lb=strlen(c); 33 KMP(); 34 int st=0,ans=0; 35 for(int i=1;i<=la;i++){ 36 if(w[i-1]==lb-1 && i-st>=lb){//截取 37 st=i; 38 ans++; 39 } 40 } 41 printf("%d\n",ans); 42 } 43 return 0; 44 }
从隔壁看到了有趣的KMP改
http://blog.csdn.net/orion_rigel/article/details/52434301
标签:
原文地址:http://www.cnblogs.com/SilverNebula/p/5840271.html