思路: KMP
#include #include char a[1005], b[1005];int fail[1005];int lena, lenb;int cnt;void getfail(){ fail[0] = -1; int i, j; for(i = 1, j = -1; i < lenb; i ++) { while(j >= 0 && b[j + 1] != b[i]) { j = fail[j]; } if(b[j + 1] == b[i]) j ++; fail[i] = j; } return ;}void kmp(){ getfail(); int i, j; for(i = 0, j = 0; i < lena; i ++) { while(j && b[j] != a[i]) { j = fail[j - 1] + 1; } if(b[j] == a[i]) j ++; if(j == lenb) { cnt ++; if(i + lenb < lena) j = 0; else return ; } }}int main(int argc, char const *argv[]){ while(~scanf("%s", a) && strcmp(a, "#")) { scanf("%s", b); lena = strlen(a); lenb = strlen(b); cnt = 0; kmp(); printf("%d\n", cnt); memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); } return 0;}