求一个串中有多少重复字串?如ababab中结果为3,a = ab。
方法:利用KMP的预处理得出数组p[i],很容易得出a长度为len - p[len]。
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <time.h>
#include <cstdio>
#include <math.h>
#include <iomanip>
#include <cstdlib>
#include <limits.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
#define LL long long
#define MIN INT_MIN
#define MAX INT_MAX
#define PI acos(-1.0)
#define FRE freopen("input.txt","r",stdin)
#define FF freopen("output.txt","w",stdout)
#define N 1000005
char str[N];
int p[N];
int main () {
while (scanf("%s",str+1)) {
if (str[1] == '.') break;
int n = strlen(str+1);
int i,j = 0;
p[1] = 0;
for (i = 2; i <= n; i++) {
while (j > 0 && str[i] != str[j+1])
j = p[j];
if (str[i] == str[j+1]) j++;
p[i] = j;
}
if (n % (n - p[n]) == 0)
printf("%d\n",n/(n-p[n]));
else puts("1");
}
return 0;
}
本文介绍了一种使用KMP算法来计算字符串中重复子串数量的方法。通过KMP的预处理步骤得到p数组,进而计算出特定子串的出现次数。适用于字符串匹配和分析场景。
645

被折叠的 条评论
为什么被折叠?



