标签:while cstring lag reg span iostream mes ems cout
思路:
简单KMP
#include<cstdio> #include<iostream> #include<string> #include<cstring> using namespace std; inline int qread(){ register int ch = getchar(), x = 0, flag = 0; while(ch < ‘0‘ || ch > ‘9‘) {if(ch == ‘-‘) flag = 1; ch = getchar();} while(ch >= ‘0‘ && ch <= ‘9‘) x = 10 * x + ch - 48, ch = getchar(); return flag ? -x : x; } char B[1010], A[1010]; int nxt[1010], M, N; void findnxt(){ int j = 0; for(int i = 1; i < M; ++i){ while(j > 0 && B[j + 1] != B[i + 1]) j = nxt[j]; if(B[j + 1] == B[i + 1]) ++j; nxt[i + 1] = j; } } int KMP(){ int j = 0, cnt = 0; for(int i = 0; i < N; ++i){ while(j > 0 && B[j + 1] != A[i + 1]) j = nxt[j]; if(B[j + 1] == A[i + 1]) ++j; if(j == M){cnt++; j = 0;} } return cnt; } int main(void){ while(1){ memset(nxt, 0, sizeof(nxt)); scanf("%s", A + 1); if(A[1] == ‘#‘) return 0; scanf("%s", B + 1); N = strlen(A + 1), M = strlen(B + 1); findnxt(); cout << KMP() << endl; } }
标签:while cstring lag reg span iostream mes ems cout
原文地址:https://www.cnblogs.com/junk-yao-blog/p/9509392.html