代码
1 #include <iostream> 2 #include <string> 3 #include <typeinfo> 4 #include <vector> 5 using namespace std; 6 7 int KMP(const string &pattern,const string &str) 8 { 9 const int len1 = pattern.length(); 10 const int len2 = str.length(); 11 vector<int> next(len1); 12 next[0]=0; 13 int i,j,k; 14 for (i=1;i<len1;i++) 15 { 16 k=next[i-1]; 17 while (pattern[i] != pattern[k]&&k!=0) 18 { 19 k=next[k-1]; 20 } 21 if(pattern[i] == pattern[k]) 22 next[i]=k+1; 23 else 24 next[i]=0; 25 } 26 i=j=0; 27 int mycount=0; 28 while (j < len2) 29 { 30 if (pattern[i]!=str[j]) 31 { 32 if (i==0) 33 { 34 i=0; 35 j++; 36 } 37 else 38 i=next[i-1]; 39 } 40 else 41 { 42 i++; 43 j++; 44 if(pattern[i] == '