题目链接:http://poj.org/problem?id=2406
题意:给出一个字符串 问它最多由多少相同的字串组成。
思路:用next数组,如果n%(n-next[n])==0,则存在重复连续子串,长度为n-next[n],如果不存在那么就只能使循环节为自己。
代码:
#include <cstdio>
#include <cmath>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <numeric>
#include <set>
#include <string>
#include <cctype>
#include <sstream>
#define INF 0x3f3f3f3f
#define INF 0x3f3f3f3f
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long LL;
typedef pair<LL, LL> P;
const int maxn = 1e6 + 5;
const int mod = 1e8 + 7;
int Next[maxn];
char T[maxn];
int n;
void getNext() {
int j, k;
j = 0;
k = -1;
Next[0] = -1;
while(j < n)
if(k == -1 || T[j] == T[k])
Next[++j] = ++k;
else
k = Next[k];
}
int main() {
//freopen ("in.txt", "r", stdin);
while (~scanf ("%s", T)) {
if (T[0]=='.') break;
n = strlen(T);
getNext();
if (n % (n - Next[n]) == 0)
printf ("%d\n",n / (n - Next[n]));
else printf ("1\n");
}
return 0;
}
本文介绍了解决 POJ 2406 题目的方法,通过使用 next 数组来判断一个字符串是否由多个相同的子串构成。详细解释了如何计算 next 数组并判断字符串的周期性。
&spm=1001.2101.3001.5002&articleId=78243717&d=1&t=3&u=b54cba02dbf34512b3a8922c71ae98af)
1076

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



