代码
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] == '\0') 45 { 46 mycount++; 47 i=next[len1-1];//为什么取pattern最后一个字符的next,自己想 48 //i赋值位next[len1-1]是为了防止j回溯 49 } 50 } 51 } 52 53 return mycount; 54 } 55 56 int main() 57 { 58 int n; 59 string pattern,str; 60 while (cin >> n) 61 { 62 while (n--) 63 { 64 cin >> pattern >> str; 65 cout << KMP(pattern,str)<<endl; 66 } 67 } 68 return 0; 69 }