KMP裸題ide
(極限5分鐘A題)spa
1 /** 2 freopen("in.in", "r", stdin); 3 freopen("my.out", "w", stdout); 4 */ 5 //// ///////////////////////////// 6 #include <cstdio> 7 #include <cstring> 8 const int N = 1010; 9 10 int nex[N]; 11 char s[N], p[N]; 12 13 int main() { 14 while(scanf("%s", s)) { 15 if(s[0] == '#') break; 16 scanf("%s", p); 17 int ans = 0; 18 nex[0] = 0; 19 for(int i = 1, j = 0; i < strlen(p); i++) { 20 while(j && p[i] != p[j]) { 21 j = nex[j - 1]; 22 } 23 if(p[i] == p[j]) j++; 24 nex[i] = j; 25 } 26 for(int i = 0, j = 0; i < strlen(s); i++) { 27 while(j && s[i] != p[j]) { 28 j = nex[j - 1]; 29 } 30 if(s[i] == p[j]) j++; 31 if(j == strlen(p)) { 32 ans++; 33 j = 0; 34 } 35 } 36 printf("%d\n", ans); 37 } 38 return 0; 39 }