1 // HDOJ 2087 KMP算法 2 #include<iostream> 3 using namespace std; 4 5 #include<string> 6 7 void nextval(char s2[],int next[],int len) 8 { 9 next[1] = 0; 10 int i = 1,j = 0; 11 while(i < len)//这里是小于号而不是小于等于是因为里面有自加,防止越界! 12 { 13 if(j == 0 || s2[i] == s2[j]) 14 { 15 ++i; 16 ++j; 17 if(s2[i] != s2[j]) next[i] = j; 18 else next[i] = next[j]; 19 } 20 else j = next[j]; 21 } 22 } 23 24 int KMP(char s1[],char s2[],int len1,int len2,int next[],int pos) 25 { 26 int i = pos,j = 1; 27 while(i <= len1 && j <= len2) 28 { 29 if(j == 0 || s1[i] == s2[j]) 30 { 31 ++i; 32 ++j; 33 } 34 else j = next[j]; 35 } 36 if(j > len2) return i; 37 else return 0; 38 } 39 40 int main() 41 { 42 string s1,s2; 43 while(cin>>s1 && s1 != "#") 44 { 45 cin>>s2; 46 int next[s2.size()+1],c = 0,pp = 0; 47 next[0] = -1; 48 char c1[s1.size()+1],c2[s2.size()+1]; 49 for(int i = 1;i <= s1.size();++i) c1[i] = s1[i-1]; 50 for(int i = 1;i <= s2.size();++i) c2[i] = s2[i-1]; 51 nextval(c2,next,s2.size()); 52 for(int pos = 1;pos <= s1.size();) 53 { 54 pp = KMP(c1,c2,s1.size(),s2.size(),next,pos); 55 if(pp) 56 { 57 ++c; 58 pos = pp; 59 } 60 else break; 61 } 62 cout<<c<<endl; 63 } 64 65 return 0; 66 }