本文共 1388 字,大约阅读时间需要 4 分钟。
为了解决问题,我们需要计算给定字符串W在较长字符串T中的出现次数。为了高效地完成这一任务,我们可以使用KMP算法,这是一种线性时间复杂度的字符串匹配算法,特别适合处理长文本。
#include#include #include #include #include #include using namespace std;int main() { int N; scanf("%d", &N); while (N--) { char P[10010], T[1000010]; int lenP, lenT; scanf("%s%s", P, T); lenP = strlen(P); lenT = strlen(T); if (lenP == 0) { printf("0\n"); continue; } if (lenT < lenP) { printf("0\n"); continue; } int next[lenP + 1]; int j = 0; for (int i = 1; i <= lenP; ++i) { while (j > 0 && P[j] != P[i]) { j = next[j]; } if (P[j] == P[i]) { j++; } next[i] = j; } int ans = 0, i = 1, j = 1; while (i <= lenT) { if (P[j] == T[i]) { if (j == lenP) { ans++; j = next[j] + 1; i++; } else { i++; j++; } } else { if (j == 1) { i++; } else { j = next[j - 1]; } } } printf("%d\n", ans); } return 0;}
next,记录每个位置的最大前缀长度。通过遍历W,使用双指针技巧来构建前缀函数。这种方法确保了在处理长字符串时的高效性,能够快速准确地统计字符串W在T中的出现次数。
转载地址:http://cbvfk.baihongyu.com/